Reputation: 1329
I am currently moving a file in java in the following way:
private static void moveFile(String fileName, String folderName) {
String name= fileName.substring(fileName.lastIndexOf('\\'), fileName.length());
new File(fileName).renameTo(new File(folderName+ File.separator + name));
}
Is there any faster way of doing this? I need to optimize this code.
Upvotes: 2
Views: 2505
Reputation: 718788
Is there any faster way of doing this? I need to optimize this code.
No, there isn't.
Files.renameTo
is a better API1, but it isn't faster.
The performance bottleneck in renaming files is the performance of file system itself. There is no scope for optimizing / improving performance in Java ... unless you can avoid the need to rename the file in the first place.
1 - If the operation fails, then you will get an exception that attempts to explain the failure. By contrast, with File.rename
you just get a boolean
result; i.e. no explanation of what went wrong.
Upvotes: 1
Reputation: 4011
As others pointed out, if you are using Java 8 you should take a look at Files.move(Path, Path, CopyOption...)
: https://docs.oracle.com/javase/8/docs/api/java/nio/file/Files.html#move-java.nio.file.Path-java.nio.file.Path-java.nio.file.CopyOption...-
Here's a simple example:
private static void moveFile(String fileName, String folderName) {
Path src = Paths.get(fileName); // fileName is the absolute path.
Path dest = Paths.get(folderName); // folderName is the absolute path.
Files.move(src, dest);
// Or if you want to replace an existing file with the same name:
// Files.move(src, dest, CopyOption.REPLACE_EXISTING);
}
Upvotes: 1
Reputation: 1434
try with this
Path source = ...
Path newdir = ...
Files.move(source, newdir.resolve(source.getFileName()), REPLACE_EXISTING);
Upvotes: 2