如何在Java中将文件从一个位置移动到另一个位置?

pma*_*mad 81 java file move

如何将文件从一个位置移动到另一个位置?当我运行我的程序时,在该位置创建的任何文件都会自动移动到指定位置.我如何知道移动了哪个文件?

提前致谢!

Thi*_*ilo 115

myFile.renameTo(new File("/the/new/place/newName.file"));
Run Code Online (Sandbox Code Playgroud)

File#renameTo可以做到这一点(它不仅可以重命名,还可以在目录之间移动,至少在同一个文件系统上).

重命名此抽象路径名表示的文件.

此方法行为的许多方面本质上依赖于平台:重命名操作可能无法将文件从一个文件系统移动到另一个文件系统,它可能不是原子的,如果具有目标抽象路径名的文件可能不会成功已经存在.应始终检查返回值以确保重命名操作成功.

如果您需要更全面的解决方案(例如想要在磁盘之间移动文件),请查看Apache Commons FileUtils #moveverFile

  • myFile.renameTo(新文件("/// new/place/newname.file")); (8认同)
  • 是的,不要只提供新的父目录.并确保那里的路径已经存在. (4认同)
  • 请注意,此命令不会更新对象`myFile`的路径.所以它将指向一个不再存在的文件. (2认同)
  • @JulienKronegg:这可能取决于您的OS /文件系统。我认为在Linux中,您可以移动(或删除)当前打开的文件(并继续通过现有文件句柄访问它们),但不能在Windows上。 (2认同)

mic*_*cha 60

使用Java 7或更高版本,您可以使用Files.move(from, to, CopyOption... options).

例如

Files.move(Paths.get("/foo.txt"), Paths.get("bar.txt"), StandardCopyOption.REPLACE_EXISTING);
Run Code Online (Sandbox Code Playgroud)

有关详细信息,请参阅文件文档


Pra*_*V R 7

爪哇 6

public boolean moveFile(String sourcePath, String targetPath) {

    File fileToMove = new File(sourcePath);

    return fileToMove.renameTo(new File(targetPath));
}
Run Code Online (Sandbox Code Playgroud)

Java 7(使用 NIO)

public boolean moveFile(String sourcePath, String targetPath) {

    boolean fileMoved = true;

    try {

        Files.move(Paths.get(sourcePath), Paths.get(targetPath), StandardCopyOption.REPLACE_EXISTING);

    } catch (Exception e) {

        fileMoved = false;
        e.printStackTrace();
    }

    return fileMoved;
}
Run Code Online (Sandbox Code Playgroud)


Pio*_*otr 6

File.renameTofrom Java IO 可用于在 Java 中移动文件。另请参阅此 SO 问题


Der*_*ike 5

要移动文件,您还可以使用Jakarta Commons IOs FileUtils.moveFile

如果出错,它会抛出一个IOException,所以当没有抛出异常时你知道该文件被移动了.


man*_*ama 5

只需添加源和目标文件夹路径。

它将所有文件和文件夹从源文件夹移动到目标文件夹。

    File destinationFolder = new File("");
    File sourceFolder = new File("");

    if (!destinationFolder.exists())
    {
        destinationFolder.mkdirs();
    }

    // Check weather source exists and it is folder.
    if (sourceFolder.exists() && sourceFolder.isDirectory())
    {
        // Get list of the files and iterate over them
        File[] listOfFiles = sourceFolder.listFiles();

        if (listOfFiles != null)
        {
            for (File child : listOfFiles )
            {
                // Move files to destination folder
                child.renameTo(new File(destinationFolder + "\\" + child.getName()));
            }

            // Add if you want to delete the source folder 
            sourceFolder.delete();
        }
    }
    else
    {
        System.out.println(sourceFolder + "  Folder does not exists");
    }
Run Code Online (Sandbox Code Playgroud)