标准简洁的方式在Java中复制文件? [英] Standard concise way to copy a file in Java?

查看:115
本文介绍了标准简洁的方式在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语言的边界内不涉及执行OS特定的命令)?也许在一些可靠的开源实用程序包中,至少会掩盖这个底层实现并提供一个单行解决方案?

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例程将直接复制到OS /文件系统,而不是通过读取和写入通过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中复制文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆