通道会减慢读取速度吗?

does channels slow the read?

我的印象是使用 FileChannel 和 BytBuffer 会加快读取时间,但它似乎比从文件流读取慢得多。我是不是做错了什么?

FileInputStream fis = new FileInputStream("C:\Users\blah\Desktop\del\pg28054.txt");
        FileOutputStream fos = new FileOutputStream("C:\Users\blah\Desktop\del\readme.txt");

        FileChannel fcin = fis.getChannel();
        FileChannel fcout = fos.getChannel();

        ByteBuffer buffer = ByteBuffer.allocate(1024);
        long startTime = System.currentTimeMillis();
        long endtime = System.currentTimeMillis();
        while(true){
            buffer.clear();
            int r = fcin.read(buffer);
            if(r==-1){
                break;
            }
            buffer.flip();
            fcout.write(buffer);
        }
        endtime = System.currentTimeMillis();
        System.out.println("time to read and write(ms) " + (endtime - startTime));

以上在 108 毫秒内完成,而下面的实现在 43 毫秒内完成

        long startTime;
        long endtime;
        FileInputStream fis1 = new FileInputStream("C:\Users\blah\Desktop\del\pg28054.txt");
        FileOutputStream fos1 = new FileOutputStream("C:\Users\blah\Desktop\del\readme1.txt");

        byte b[] = null;

        startTime = System.currentTimeMillis();
        while(true){
            b = new byte[1024];
            int r = fis1.read(b);
            if(r==-1){
                break;
            }
            fos1.write(b);
        }

        endtime = System.currentTimeMillis();
        System.out.println("time to read and write(ms) " + (endtime - startTime));

除了关于基准测试质量的非常准确的评论之外,关于 Channels 或 ByteBuffers 的任何东西都没有本质上比流更快。有一些选项可以使事情执行得更快。例如,您可以使用 FileChannel.transferFrom method to transfer the content. Another example would be to use a direct ByteBuffer 来传输内容。