简体   繁体   中英

does channels slow the read?

I was under the impression that using FileChannel and BytBuffer would speed the read time but it seems to be significantly slower than reading from a filestream. Am I doing something wrong here?

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));

The above completes in 108 ms where are the below implementation does it in 43 ms

        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));

Aside from the very accurate comments about the quality of your benchmark, there is nothing about Channels or ByteBuffers that is inherently faster than streams. There are options which can make things perform faster. For example, you could use the FileChannel.transferFrom method to transfer the content. Another example would be to use a direct ByteBuffer to transfer the content.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM