繁体   English   中英

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

[英]How do I move a file from one location to another in Java?

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

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

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

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

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

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

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

例如

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

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

爪哇 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;
}

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

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

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

    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");
    }

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

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

Files.move(source, target, REPLACE_EXISTING);

您可以使用Files对象

阅读有关 文件的更多信息

尝试这个 :-

  boolean success = file.renameTo(new File(Destdir, file.getName()));

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

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

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

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

Files.move(source, target, REPLACE_EXISTING);

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

// 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;
    }       
}

请试试这个。

 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;
            }

暂无
暂无

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

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