java - renameTo() not working -
java - renameTo() not working -
i need rename file replacing -
_
in file name.
suppose if file name ab-9.xml
, should ab_9.xml
.
renameto()
not working me. there other way that? here code:
file replacecheracter(file file) { file oldpath = new file(file.getpath()) string filepath = file.getpath() if(filepath.contains("-")){ string newfilepath = filepath.replace("-", "_") if(oldpath.renameto(newfilepath)) { system.out.println("renamed"); } else { system.out.println("error"); } } homecoming oldpath }
you should consider using java.nio.file package:
final path file = paths.get("path\\to\\your-file.txt"); files.move(file, file.resolvesibling(file.getfilename().tostring().replace("-", "_")));
used handy function path#resolvesibling() sec argument files#move().
explanation:
path#resolvesibling()
takes directory path of path
object called on, , swaps lastly part (the actual file name) supplied argument (the new, modified file name in case). using behavior sec argument files#move()
result in move source directory , target directory same, renames file.
see the java tutorials - file i/o farther info on this.
java groovy
Comments
Post a Comment