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

查看:28
本文介绍了在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中复制文件的标准简洁方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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