Java : copy files efficiently with channel

标签 java io nio file-copying

我读了一篇关于转移副本的文章 在https://www.ibm.com/developerworks/library/j-zerocopy/ .建议用户 channel 进行IO操作。

复制文件操作的基准在 https://baptiste-wicht.com/posts/2010/08/file-copy-in-java-benchmark.html

根据基准测试,我可以使用 nio buffernio trasfer

我还阅读了FileChannel does buffereing in the OS level 这里How to implement a buffered / batched FileChannel in Java?

使用缓冲区或不使用缓冲区复制文件的效率更高。

nio 缓冲区代码

public static void nioBufferCopy(File sourceFile, File targetFile, int BUFFER) {
        FileChannel inputChannel = null;
        FileChannel outputChannel = null;
        try {
            inputChannel = new FileInputStream(sourceFile).getChannel();
            outputChannel = new FileOutputStream(targetFile).getChannel();
            ByteBuffer buffer = ByteBuffer.allocateDirect(BUFFER);
            while (inputChannel.read(buffer) != -1) {
                buffer.flip();          
                while(buffer.hasRemaining()){
                    outputChannel.write(buffer);
                }           
                buffer.clear();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
           //close resource
        }
}

nio 传输代码

public void copyFileWithChannels(File aSourceFile, File aTargetFile) {              
        FileChannel inChannel = null;
        FileChannel outChannel = null;
        FileInputStream inStream = null;
        FileOutputStream outStream = null;      
        try {
            inStream = new FileInputStream(aSourceFile);
            inChannel = inStream.getChannel();
            outStream = new  FileOutputStream(aTargetFile);        
            outChannel = outStream.getChannel();
            long bytesTransferred = 0;
            while(bytesTransferred < inChannel.size()){
                bytesTransferred += inChannel.transferTo(bytesTransferred, inChannel.size(), outChannel);
            }
        }       
        catch (Exception e) {
            e.printStackTrace();
        }
        finally {
            //close resource
        }              
}

最佳答案

这个问题之前有人问过:

Java NIO FileChannel versus FileOutputstream performance / usefulness

TL.DR.:运行 JVM 很重要,但主要是 java.nio 稍微快一些。

关于Java : copy files efficiently with channel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44150483/

相关文章:

java - 如何在特定条件下停止 Gradle 或 Maven 构建

input - 打印后用户输入

java - 为什么要在 java nio 的 `selector.selectedKeys().iterator()` 中删除 key ?

Java NIO 与 sql 数据库

java - 当为映射文件打开 FileOutputStream 时从 java.nio.MappedByteBuffer 读取会导致 "unsafe memory access"错误

使用 commons-digester 进行解析时出现 java.lang.NumberFormatException

java - 按住箭头键时 TableView 会变得困惑

java - 如何在 Windows 上检测以太网电缆是否与 Java 连接

python - 打开已经打开的文件不会引发异常

java - 在 Java 中测量线程 I/O