114

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

4

12 回答 12

156
myFile.renameTo(new File("/the/new/place/newName.file"));

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

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

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

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

于 2011-01-10T09:27:09.173 回答
74

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

例如

Files.move(Paths.get("/foo.txt"), Paths.get("bar.txt"), StandardCopyOption.REPLACE_EXISTING);

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

于 2014-05-22T16:55:39.097 回答
8

爪哇 6

public boolean moveFile(String sourcePath, String targetPath) {

    File fileToMove = new File(sourcePath);

    return fileToMove.renameTo(new File(targetPath));
}

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;
}
于 2018-04-19T05:30:01.590 回答
6

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

于 2011-01-10T09:25:52.627 回答
5

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

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

于 2011-01-10T09:30:42.850 回答
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");
    }
于 2016-03-15T09:59:24.360 回答
3
Files.move(source, target, REPLACE_EXISTING);

您可以使用Files对象

阅读有关文件的更多信息

于 2017-06-10T13:08:14.850 回答
2

您可以为该任务执行外部工具(例如copy在 Windows 环境中),但是为了保持代码的可移植性,一般方法是:

  1. 将源文件读入内存
  2. 将内容写入新位置的文件
  3. 删除源文件

File#renameTo只要源和目标位置在同一个卷上,它就可以工作。我个人会避免使用它将文件移动到不同的文件夹。

于 2011-01-10T09:28:51.740 回答
2

试试这个 :-

  boolean success = file.renameTo(new File(Destdir, file.getName()));
于 2017-06-08T04:01:44.523 回答
1

你可以试试这个..干净的解决方案

Files.move(source, target, REPLACE_EXISTING);
于 2020-08-05T09:56:21.193 回答
0

如果其中存在逻辑,则仅使用替换文件编写此方法以在我自己的项目中执行此操作。

// we use the older file i/o operations for this rather than the newer jdk7+ Files.move() operation
private boolean moveFileToDirectory(File sourceFile, String targetPath) {
    File tDir = new File(targetPath);
    if (tDir.exists()) {
        String newFilePath = targetPath+File.separator+sourceFile.getName();
        File movedFile = new File(newFilePath);
        if (movedFile.exists())
            movedFile.delete();
        return sourceFile.renameTo(new File(newFilePath));
    } else {
        LOG.warn("unable to move file "+sourceFile.getName()+" to directory "+targetPath+" -> target directory does not exist");
        return false;
    }       
}
于 2018-01-08T15:47:16.683 回答
0

请试试这个。

 private boolean filemovetoanotherfolder(String sourcefolder, String destinationfolder, String filename) {
            boolean ismove = false;
            InputStream inStream = null;
            OutputStream outStream = null;

            try {

                File afile = new File(sourcefolder + filename);
                File bfile = new File(destinationfolder + filename);

                inStream = new FileInputStream(afile);
                outStream = new FileOutputStream(bfile);

                byte[] buffer = new byte[1024 * 4];

                int length;
                // copy the file content in bytes
                while ((length = inStream.read(buffer)) > 0) {

                outStream.write(buffer, 0, length);

                }


                // delete the original file
                afile.delete();
                ismove = true;
                System.out.println("File is copied successful!");

            } catch (IOException e) {
                e.printStackTrace();
            }finally{
               inStream.close();
               outStream.close();
            }
            return ismove;
            }
于 2020-03-06T05:42:20.750 回答