用Java复制文件的标准简洁方法?

2022-01-20 00:00:00 复制 file java

一直困扰着我的是,在 Java 中复制文件的唯一方法是打开流、声明缓冲区、读入一个文件、循环通过它,然后将其写入另一个流.网络上充斥着类似但仍然略有不同的此类解决方案的实现.

It has always bothered me that the only way to copy a file in Java involves opening streams, declaring a buffer, reading in one file, looping through it, and writing it out to the other steam. The web is littered with similar, yet still slightly different implementations of this type of solution.

有没有更好的方法来保持在 Java 语言的范围内(意味着不涉及执行操作系统特定的命令)?也许在一些可靠的开源实用程序包中,这至少会掩盖这个底层实现并提供一个单一的解决方案?

Is there a better way that stays within the bounds of the Java language (meaning does not involve exec-ing OS specific commands)? Perhaps in some reliable open source utility package, that would at least obscure this underlying implementation and provide a one line solution?

推荐答案

正如上面提到的工具包,Apache Commons IO 是要走的路,特别是 FileUtils.copyFile();它为您处理所有繁重的工作.

As toolkit mentions above, Apache Commons IO is the way to go, specifically FileUtils.copyFile(); it handles all the heavy lifting for you.

作为后记,请注意最近的 FileUtils 版本(例如 2.0.1 版本)添加了使用 NIO 来复制文件;NIO 可以显着提高文件复制性能,很大程度上是因为 NIO 例程推迟直接复制到操作系统/文件系统,而不是通过 Java 层读取和写入字节来处理它.因此,如果您正在寻找性能,可能值得检查一下您使用的是最新版本的 FileUtils.

And as a postscript, note that recent versions of FileUtils (such as the 2.0.1 release) have added the use of NIO for copying files; NIO can significantly increase file-copying performance, in a large part because the NIO routines defer copying directly to the OS/filesystem rather than handle it by reading and writing bytes through the Java layer. So if you're looking for performance, it might be worth checking that you are using a recent version of FileUtils.

相关文章