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

时间:2022-05-29 08:08:18

How do you move a file from one location to another? When I run my program any file created in that location automatically moves to the specified location. How do I know which file is moved?

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

Thanks in advance!

提前谢谢!

10 个解决方案

#1


78  

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

File#renameTo does that (it can not only rename, but also move between directories, at least on the same file system).

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

Renames the file denoted by this abstract pathname.

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

Many aspects of the behavior of this method are inherently platform-dependent: The rename operation might not be able to move a file from one filesystem to another, it might not be atomic, and it might not succeed if a file with the destination abstract pathname already exists. The return value should always be checked to make sure that the rename operation was successful.

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

If you need a more comprehensive solution (such as wanting to move the file between disks), look at Apache Commons FileUtils#moveFile

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

#2


41  

With Java 7 or newer you can use Files.move(from, to, CopyOption... options).

使用Java 7或更新版本,您可以使用文件。(从,移到,CopyOption……选项)。

E.g.

如。

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

See the Files documentation for more details

有关更多细节,请参阅文件文档

#3


4  

File.renameTo from Java IO can be used to move a file in Java. Also see this SO question.

文件。Java IO中的renameTo可用于在Java中移动文件。也看到这个问题。

#4


4  

To move a file you could also use Jakarta Commons IOs FileUtils.moveFile

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

On error it throws an IOException, so when no exception is thrown you know that that the file was moved.

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

#5


2  

You could execute an external tool for that task (like copy in windows environments) but, to keep the code portable, the general approach is to:

您可以为该任务执行一个外部工具(如windows环境中的复制),但是,为了使代码具有可移植性,一般的方法是:

  1. read the source file into memory
  2. 将源文件读入内存
  3. write the content to a file at the new location
  4. 将内容写入新位置的文件中
  5. delete the source file
  6. 删除源文件

File#renameTo will work as long as source and target location are on the same volume. Personally I'd avoid using it to move files to different folders.

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

#6


2  

Just add the source and destination folder paths.

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

It will move all the files and folder from source folder to destination folder.

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

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

#7


1  

Try this :-

试试这个:

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

#8


0  

Files.move(source, target, REPLACE_EXISTING);

You can use the Files object

您可以使用file对象

Read more about Files

阅读更多关于文件

#9


0  

Wrote this method to do this very thing on my own project only with the replace file if existing logic in it.

只在我自己的项目上使用替换文件(如果其中有逻辑的话)编写此方法来完成此任务。

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

#10


0  

Java 6

Java 6

public boolean moveFile(String sourcePath, String targetPath) {

    File fileToMove = new File(sourcePath);

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

Java 7 (Using NIO)

Java 7(使用NIO)

public boolean moveFile(String sourcePath, String targetPath) {

    boolean flag = true;

    try {

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

    } catch (Exception e) {

        flag = false;
        e.printStackTrace();
    }

    return flag;
}

#1


78  

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

File#renameTo does that (it can not only rename, but also move between directories, at least on the same file system).

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

Renames the file denoted by this abstract pathname.

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

Many aspects of the behavior of this method are inherently platform-dependent: The rename operation might not be able to move a file from one filesystem to another, it might not be atomic, and it might not succeed if a file with the destination abstract pathname already exists. The return value should always be checked to make sure that the rename operation was successful.

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

If you need a more comprehensive solution (such as wanting to move the file between disks), look at Apache Commons FileUtils#moveFile

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

#2


41  

With Java 7 or newer you can use Files.move(from, to, CopyOption... options).

使用Java 7或更新版本,您可以使用文件。(从,移到,CopyOption……选项)。

E.g.

如。

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

See the Files documentation for more details

有关更多细节,请参阅文件文档

#3


4  

File.renameTo from Java IO can be used to move a file in Java. Also see this SO question.

文件。Java IO中的renameTo可用于在Java中移动文件。也看到这个问题。

#4


4  

To move a file you could also use Jakarta Commons IOs FileUtils.moveFile

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

On error it throws an IOException, so when no exception is thrown you know that that the file was moved.

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

#5


2  

You could execute an external tool for that task (like copy in windows environments) but, to keep the code portable, the general approach is to:

您可以为该任务执行一个外部工具(如windows环境中的复制),但是,为了使代码具有可移植性,一般的方法是:

  1. read the source file into memory
  2. 将源文件读入内存
  3. write the content to a file at the new location
  4. 将内容写入新位置的文件中
  5. delete the source file
  6. 删除源文件

File#renameTo will work as long as source and target location are on the same volume. Personally I'd avoid using it to move files to different folders.

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

#6


2  

Just add the source and destination folder paths.

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

It will move all the files and folder from source folder to destination folder.

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

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

#7


1  

Try this :-

试试这个:

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

#8


0  

Files.move(source, target, REPLACE_EXISTING);

You can use the Files object

您可以使用file对象

Read more about Files

阅读更多关于文件

#9


0  

Wrote this method to do this very thing on my own project only with the replace file if existing logic in it.

只在我自己的项目上使用替换文件(如果其中有逻辑的话)编写此方法来完成此任务。

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

#10


0  

Java 6

Java 6

public boolean moveFile(String sourcePath, String targetPath) {

    File fileToMove = new File(sourcePath);

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

Java 7 (Using NIO)

Java 7(使用NIO)

public boolean moveFile(String sourcePath, String targetPath) {

    boolean flag = true;

    try {

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

    } catch (Exception e) {

        flag = false;
        e.printStackTrace();
    }

    return flag;
}