Standard concise way to copy a file in Java?(用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.
这篇关于用Java复制文件的标准简洁方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:用Java复制文件的标准简洁方法?
- Java包名称中单词分隔符的约定是什么? 2022-01-01
- Spring Boot连接到使用仲裁器运行的MongoDB副本集 2022-01-01
- 将log4j 1.2配置转换为log4j 2配置 2022-01-01
- Eclipse 插件更新错误日志在哪里? 2022-01-01
- 如何使用WebFilter实现授权头检查 2022-01-01
- Jersey REST 客户端:发布多部分数据 2022-01-01
- Safepoint+stats 日志,输出 JDK12 中没有 vmop 操作 2022-01-01
- 从 finally 块返回时 Java 的奇怪行为 2022-01-01
- value & 是什么意思?0xff 在 Java 中做什么? 2022-01-01
- C++ 和 Java 进程之间的共享内存 2022-01-01