如何在将文件移动到Java中的另一个目录时为文件指定新名称?

Dau*_*aud 1 java apache-commons

Apache Commons IO 有一个方法可以将文件移动到另一个目录,这个目录不允许我在目标目录中为它指定一个新名称:

public static void moveFileToDirectory(File srcFile, File destDir, boolean createDestDir)
                                throws IOException
Run Code Online (Sandbox Code Playgroud)

我不想先重命名该文件,然后将该文件移动到另一个目录.有没有办法通过任何库方法中的单个语句来执行此操作?(我想要一个单一的方法,以避免任何并发问题,这将由库自动处理)

sol*_*4me 5

从Java7开始,您可以使用Files.move.例如

Path source = Paths.get(src);
Path target = Paths.get(dest);
Files.move(source, target, REPLACE_EXISTING, COPY_ATTRIBUTES);
Run Code Online (Sandbox Code Playgroud)


Mic*_*ael 5

Apache Commons IO FIleUtils 类具有moveFile方法。您只需指定“新名称”作为destFile参数的一部分。

FileUtils.moveFile(
      FileUtils.getFile("src/test/old-resources/oldname.txt"), 
      FileUtils.getFile("src/test/resources/renamed.txt"));
Run Code Online (Sandbox Code Playgroud)

正如 Ian Roberts 在他的回答中正确地说的那样,如果您知道目标存在,则可以srcFile.renameTo(destFile)在文件上使用该方法,但 Commons IO 类会为您检查/创建文件夹。如果 renameTo 由于任何原因失败(返回 false),它会在后台使用 FileUtils 自己的copyFile方法。如果我们查看方法注释,我们可以清楚地看到“如果目标文件不存在,则创建保存目标文件的目录”。

这是 FileUtils moveFile 方法的源代码,以便您可以清楚地看到它为您提供的内容:

2943    public static void moveFile(final File srcFile, final File destFile) throws IOException {
2944        if (srcFile == null) {
2945            throw new NullPointerException("Source must not be null");
2946        }
2947        if (destFile == null) {
2948            throw new NullPointerException("Destination must not be null");
2949        }
2950        if (!srcFile.exists()) {
2951            throw new FileNotFoundException("Source '" + srcFile + "' does not exist");
2952        }
2953        if (srcFile.isDirectory()) {
2954            throw new IOException("Source '" + srcFile + "' is a directory");
2955        }
2956        if (destFile.exists()) {
2957            throw new FileExistsException("Destination '" + destFile + "' already exists");
2958        }
2959        if (destFile.isDirectory()) {
2960            throw new IOException("Destination '" + destFile + "' is a directory");
2961        }
2962        final boolean rename = srcFile.renameTo(destFile);
2963        if (!rename) {
2964            copyFile( srcFile, destFile );
2965            if (!srcFile.delete()) {
2966                FileUtils.deleteQuietly(destFile);
2967                throw new IOException("Failed to delete original file '" + srcFile +
2968                        "' after copy to '" + destFile + "'");
2969            }
2970        }
2971    }
Run Code Online (Sandbox Code Playgroud)

来源:http://commons.apache.org/proper/commons-io/apidocs/org/apache/commons/io/FileUtils.html#moveFile(java.io.File, java.io.File)