Reading and writting a large file using Java NIO

前端 未结 2 1728
傲寒
傲寒 2021-01-27 14:57

How can I effectively read from a large file and write bulk data into a file using the Java NIO framework.

I\'m working with ByteBuffer and

2条回答
  •  Happy的楠姐
    2021-01-27 15:30

    while ((bytesCount = in.read(bytebuf)) > 0) { 
            // flip the buffer which set the limit to current position, and position to 0.
            bytebuf.flip();
            out.write(bytebuf); // Write data from ByteBuffer to file
            bytebuf.clear(); // For the next read
        }
    

    Your copy loop is not correct. It should be:

    while ((bytesCount = in.read(bytebuf)) > 0 || bytebuf.position() > 0) { 
            // flip the buffer which set the limit to current position, and position to 0.
            bytebuf.flip();
            out.write(bytebuf); // Write data from ByteBuffer to file
            bytebuf.compact(); // For the next read
        }
    

    Can anybody tell, should I follow the same procedure if my file size [is] more than 2 GB?

    Yes. The file size doesn't make any difference.

提交回复
热议问题