渠道会减慢阅读速度吗?

时间:2015-02-10 00:32:15

标签: java nio

我的印象是使用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));

1 个答案:

答案 0 :(得分:2)

除了关于基准测试质量的非常准确的评论之外,Channels或ByteBuffers没有任何内容比流更快。有些选项可以使事情表现得更快。例如,您可以使用FileChannel.transferFrom方法传输内容。另一个例子是使用direct ByteBuffer来传输内容。