博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
用Java复制文件的标准简洁方法?
阅读量:2379 次
发布时间:2019-05-10

本文共 4450 字,大约阅读时间需要 14 分钟。

本文翻译自:

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. 一直困扰我的是,用Java复制文件的唯一方法是打开流,声明一个缓冲区,读取一个文件,循环遍历它,然后将其写入另一个文件。 The web is littered with similar, yet still slightly different implementations of this type of solution. Web上充斥着类似但仍然略有不同的此类解决方案的实现。

Is there a better way that stays within the bounds of the Java language (meaning does not involve exec-ing OS specific commands)? 有没有更好的方法保持在Java语言的范围内(意味着不涉及执行特定于操作系统的命令)? Perhaps in some reliable open source utility package, that would at least obscure this underlying implementation and provide a one line solution? 也许在一些可靠的开源实用程序包中,这至少会掩盖这个底层实现并提供单行解决方案?


#1楼

参考:


#2楼

Three possible problems with the above code: 上述代码存在三个可能的问题:

  1. If getChannel throws an exception, you might leak an open stream. 如果getChannel抛出异常,则可能会泄漏打开的流。
  2. For large files, you might be trying to transfer more at once than the OS can handle. 对于大型文件,您可能尝试一次性传输比操作系统可以处理的更多文件。
  3. You are ignoring the return value of transferFrom, so it might be copying just part of the file. 您忽略了transferFrom的返回值,因此它可能只是复制文件的一部分。

This is why org.apache.tools.ant.util.ResourceUtils.copyResource is so complicated. 这就是org.apache.tools.ant.util.ResourceUtils.copyResource如此复杂的原因。 Also note that while transferFrom is OK, transferTo breaks on JDK 1.4 on Linux (see ) – Jesse Glick Jan 另请注意,虽然transferFrom没问题,但是在Linux上JDK 1.4上的transferTo中断(参见 ) - Jesse Glick Jan


#3楼

As toolkit mentions above, Apache Commons IO is the way to go, specifically . 正如上面提到的工具包,Apache Commons IO是的方法,特别是 。 ; ; it handles all the heavy lifting for you. 它为您处理所有繁重的工作。

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; 并且作为附言,请注意最新版本的FileUtils(例如2.0.1版本)已经添加了使用NIO来复制文件; , 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. ,这在很大程度上是因为NIO例程将复制直接推迟到OS /文件系统,而不是通过Java层读取和写入字节来处理它。 So if you're looking for performance, it might be worth checking that you are using a recent version of FileUtils. 因此,如果您正在寻找性能,可能需要检查您使用的是最新版本的FileUtils。


#4楼

I would avoid the use of a mega api like apache commons. 我会避免使用像apache commons这样的mega api。 This is a simplistic operation and its built into the JDK in the new NIO package. 这是一个简单的操作,它内置于新的NIO包中的JDK中。 It was kind of already linked to in a previous answer, but the key method in the NIO api are the new functions "transferTo" and "transferFrom". 它在前一个答案中已经有点联系了,但是NIO api中的关键方法是新功能“transferTo”和“transferFrom”。

One of the linked articles shows a great way on how to integrate this function into your code, using the transferFrom: 其中一篇链接文章显示了如何使用transferFrom将此功能集成到代码中的一种很好的方法:

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();        destination.transferFrom(source, 0, source.size());    }    finally {        if(source != null) {            source.close();        }        if(destination != null) {            destination.close();        }    }}

Learning NIO can be a little tricky, so you might want to just trust in this mechanic before going off and trying to learn NIO overnight. 学习NIO可能有点棘手,所以你可能想要在离开并试图一夜之间学习NIO之前就相信这个机制。 From personal experience it can be a very hard thing to learn if you don't have the experience and were introduced to IO via the java.io streams. 根据个人经验,如果您没有经验并且通过java.io流引入IO,那么学习起来可能是一件非常困难的事情。


#5楼

Note that all of these mechanisms only copy the contents of the file, not the metadata such as permissions. 请注意,所有这些机制仅复制文件的内容,而不复制权限等元数据。 So if you were to copy or move an executable .sh file on linux the new file would not be executable. 因此,如果您要在Linux上复制或移动可执行文件.sh文件,则新文件将无法执行。

In order to truly a copy or move a file, ie to get the same result as copying from a command line, you actually need to use a native tool. 为了真正复制或移动文件,即获得与从命令行复制相同的结果,您实际上需要使用本机工具。 Either a shell script or JNI. shell脚本或JNI。

Apparently, this might be fixed in java 7 - . 显然,这可以在java 7中修复 - 。 Fingers crossed! 手指交叉!


#6楼

如果您在已经使用Spring的Web应用程序中,并且如果您不想将Apache Commons IO包含在简单文件复制中,则可以使用Spring框架的 。

转载地址:http://ybexb.baihongyu.com/

你可能感兴趣的文章
10g和11g自动任务的区别
查看>>
Mysql innodb存储引擎的性能优化
查看>>
高斯信道下信号相位估计
查看>>
进程join和detach注意事项
查看>>
C++原子操作atomic库介绍
查看>>
C++多线程内存模型
查看>>
C++并发数据结构的内存回收
查看>>
转发与重定向
查看>>
隐式对象简介(转载)
查看>>
使用了request.setCharacterEncoding()方法却解决不了中文乱码原因(转载)
查看>>
读取Properties文件读取,路径,空格,中文问题
查看>>
转发与重定向的路径问题(转)
查看>>
Integer.parseInt(s) 和 Integer.valueOf(s)详细区别(转)
查看>>
Cookie 跨域访问转自(http://qingfeng825.javaeye.com/)
查看>>
深入Java核心 Java内存分配原理精讲(转)
查看>>
全面分析Java的垃圾回收机制(转)
查看>>
Struts 与 dojo 整合研究 (一)
查看>>
Servlet线程,工作原理及3.0新特性
查看>>
成为Java高手的25个学习目标
查看>>
IE6下使用JS获取路径中包含汉字的URL的一个问题(转载)
查看>>