Apache Commons IO
有一个方法可以将文件移动到另一个目录,这个目录不允许我在目标目录中为它指定一个新名称:
public static void moveFileToDirectory(File srcFile, File destDir, boolean createDestDir)
throws IOException
我不想先重命名文件,然后将文件移动到另一个目录。有没有办法通过任何库方法中的单个语句来执行此操作? (我想要一个单一的方法,以避免任何并发问题,这将由库自动处理)
答案 0 :(得分:5)
从Java7开始,您可以使用Files.move。 E.g。
Path source = Paths.get(src);
Path target = Paths.get(dest);
Files.move(source, target, REPLACE_EXISTING, COPY_ATTRIBUTES);
答案 1 :(得分:4)
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在his answer中正确地说的那样,如果您知道目标存在,则可以在文件上使用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 }
答案 2 :(得分:1)
如果您知道目标目录已经存在,那么您不需要任何外部目录,只需使用srcFile.renameTo(destFile)
- 源文件和目标文件不必位于同一目录中。
答案 3 :(得分:0)
Apache Common 有很多有用的方法。例如,你可以使用这个:
public void moveMyFile throws IOException {
FileUtils.moveFile(
FileUtils.getFile("path/to/source.txt"),
FileUtils.getFile("path/to/new destination.txt"));
}