Java中的移动/复制文件操作

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/300559/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 12:49:41  来源:igfitidea点击:

Move / Copy File Operations in Java

javafilecopymove

提问by MSumulong

Is there a standard Java library that handles common file operations such as moving/copying files/folders?

是否有处理常见文件操作(例如移动/复制文件/文件夹)的标准 Java 库?

采纳答案by Rigo Vides

Here's how to do this with java.niooperations:

以下是如何通过java.nio操作来做到这一点:

public static void copyFile(File sourceFile, File destFile) throws IOException {
    if(!destFile.exists()) {
        destFile.createNewFile();
    }

    FileChannel source = null;
    FileChannel destination = null;
    try {
        source = new FileInputStream(sourceFile).getChannel();
        destination = new FileOutputStream(destFile).getChannel();

        // previous code: destination.transferFrom(source, 0, source.size());
        // to avoid infinite loops, should be:
        long count = 0;
        long size = source.size();              
        while((count += destination.transferFrom(source, count, size-count))<size);
    }
    finally {
        if(source != null) {
            source.close();
        }
        if(destination != null) {
            destination.close();
        }
    }
}

回答by erickson

Not yet, but the New NIO (JSR 203)will have support for these common operations.

还没有,但新 NIO (JSR 203)将支持这些常见操作。

In the meantime, there are a few things to keep in mind.

在此期间,有几件事需要牢记。

File.renameTogenerally works only on the same file system volume. I think of this as the equivalent to a "mv" command. Use it if you can, but for general copy and move support, you'll need to have a fallback.

File.renameTo通常仅适用于相同的文件系统卷。我认为这相当于“mv”命令。如果可以,请使用它,但对于一般的复制和移动支持,您需要有一个后备。

When a rename doesn't work you will need to actually copy the file (deleting the original with File.deleteif it's a "move" operation). To do this with the greatest efficiency, use the FileChannel.transferToor FileChannel.transferFrommethods. The implementation is platform specific, but in general, when copying from one file to another, implementations avoid transporting data back and forth between kernel and user space, yielding a big boost in efficiency.

当重命名不起作用时,您将需要实际复制文件(如果是“移动”操作,则使用File.delete删除原始文件)。要以最高效率执行此操作,请使用FileChannel.transferToFileChannel.transferFrom方法。该实现是特定于平台的,但总的来说,当从一个文件复制到另一个文件时,实现避免在内核和用户空间之间来回传输数据,从而大大提高了效率。

回答by Pyrolistical

Check out: http://commons.apache.org/io/

查看:http: //commons.apache.org/io/

It has copy, and as stated the JDK already has move.

它有副本,并且如前所述 JDK 已经移动。

Don't implement your own copy method. There are so many floating out there...

不要实现自己的复制方法。有很多漂浮在那里......

回答by ntg

Previous answers seem to be outdated.

以前的答案似乎已经过时。

Java's File.renameTo()is probably the easiest solution for API 7, and seems to work fine. Be carefull IT DOES NOT THROW EXCEPTIONS, but returns true/false!!!

Java 的File.renameTo()可能是 API 7 最简单的解决方案,而且似乎工作正常。小心它不会抛出异常,但会返回真/假!!!

Note that there seem to be problems with it in previous versions (same as NIO).

请注意,它在以前的版本中似乎存在问题(与NIO相同)。

If you need to use a previous version, check here.

如果您需要使用以前的版本,请在此处查看

Here's an example for API7:

以下是 API7 的示例:

File f1= new File("C:\Users\.....\foo");
File f2= new File("C:\Users\......\foo.old");
System.err.println("Result of move:"+f1.renameTo(f2));

Alternatively:

或者:

System.err.println("Move:" +f1.toURI() +"--->>>>"+f2.toURI());
Path b1=Files.move(f1.toPath(),  f2.toPath(), StandardCopyOption.ATOMIC_MOVE ,StandardCopyOption.REPLACE_EXISTING ););
System.err.println("Move: RETURNS:"+b1);

回答by Dellanio

Try to use org.apache.commons.io.FileUtils(General file manipulation utilities). Facilities are provided in the following methods:

尝试使用org.apache.commons.io.FileUtils(通用文件操作实用程序)。设施以下列方式提供:

(1) FileUtils.moveDirectory(File srcDir, File destDir)=> Moves a directory.

(2) FileUtils.moveDirectoryToDirectory(File src, File destDir, boolean createDestDir)=> Moves a directory to another directory.

(3) FileUtils.moveFile(File srcFile, File destFile)=> Moves a file.

(4) FileUtils.moveFileToDirectory(File srcFile, File destDir, boolean createDestDir)=> Moves a file to a directory.

(5) FileUtils.moveToDirectory(File src, File destDir, boolean createDestDir)=> Moves a file or directory to the destination directory.

(1) FileUtils.moveDirectory(File srcDir, File destDir)=> 移动一个目录。

(2) FileUtils.moveDirectoryToDirectory(File src, File destDir, boolean createDestDir)=> 将一个目录移动到另一个目录。

(3) FileUtils.moveFile(File srcFile, File destFile)=> 移动文件。

(4) FileUtils.moveFileToDirectory(File srcFile, File destDir, boolean createDestDir)=> 将文件移动到目录。

(5) FileUtils.moveToDirectory(File src, File destDir, boolean createDestDir)=> 将文件或目录移动到目标目录。

It's simple, easy and fast.

它简单、容易且快速。

回答by Elena

Interesting observation: Tried to copy the same file via various java classes and printed time in nano seconds.

有趣的观察:试图通过各种 java 类复制同一个文件,并在纳秒内打印时间。

Duration using FileOutputStream byte stream: 4 965 078

使用 FileOutputStream 字节流的持续时间:4 965 078

Duration using BufferedOutputStream: 1 237 206

使用 BufferedOutputStream 的持续时间:1 237 206

Duration using (character text Reader: 2 858 875

使用时间(字符文本阅读器:2 858 875

Duration using BufferedReader(Buffered character text stream: 1 998 005

使用 BufferedReader 的持续时间(缓冲字符文本流:1 998 005

Duration using (Files NIO copy): 18 351 115

使用时间(文件 NIO 副本):18 351 115

when using Files Nio copy option it took almost 18 times longer!!! Nio is the slowest option to copy files and BufferedOutputStream looks like the fastest. I used the same simple text file for each class.

使用 Files Nio 复制选项时,它花费了近 18 倍的时间!!!Nio 是复制文件最慢的选项,而 BufferedOutputStream 看起来是最快的。我为每个班级使用了相同的简单文本文件。