繁体   English   中英

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

[英]How to specify a new name for a file while moving it to another directory in Java?

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

public static void moveFileToDirectory(File srcFile, File destDir, boolean createDestDir)
                                throws IOException

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

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

Path source = Paths.get(src);
Path target = Paths.get(dest);
Files.move(source, target, REPLACE_EXISTING, COPY_ATTRIBUTES);

Apache Commons IO FIleUtils类具有moveFile方法。 您只需要在destFile参数中指定“新名称”即可。

FileUtils.moveFile(
      FileUtils.getFile("src/test/old-resources/oldname.txt"), 
      FileUtils.getFile("src/test/resources/renamed.txt"));

正如伊恩·罗伯茨(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    }

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

如果您知道目标目录已经存在,那么您不需要外部任何内容,只需使用srcFile.renameTo(destFile) -源文件和目标文件不必位于同一目录中。

Apache Common具有许多有用的方法。 例如,您可以使用以下代码:

  public void moveMyFile throws IOException {
      FileUtils.moveFile(
      FileUtils.getFile("path/to/source.txt"), 
      FileUtils.getFile("path/to/new destination.txt"));
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM