Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/381.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在java中移动文件_Java_Optimization - Fatal编程技术网

在java中移动文件

在java中移动文件,java,optimization,Java,Optimization,我目前正在以以下方式移动java中的文件: 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));

我目前正在以以下方式移动java中的文件:

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));
}
有没有更快的方法?我需要优化此代码。

尝试使用此代码

         Path source = ...
         Path newdir = ...
         Files.move(source, newdir.resolve(source.getFileName()), REPLACE_EXISTING);

正如其他人所指出的,如果您使用的是Java 8,您应该查看文件。movePath、Path、CopyOption…:

下面是一个简单的例子:

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);
}
有没有更快的方法?我需要优化这个代码

不,没有

Files.renameTo是一个更好的API1,但它并不更快

重命名文件的性能瓶颈是文件系统本身的性能。在Java中没有优化/改进性能的余地。。。除非您可以避免首先重命名文件

1-如果操作失败,则会出现异常,试图解释失败。相反,使用File.rename只会得到一个布尔结果;i、 e.没有任何错误的解释。

使用Java NIO:始终是一种选择