Reading and writting a large file using Java NIO

前端 未结 2 1711
傲寒
傲寒 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条回答
  • 2021-01-27 15:23

    Note that you can simply use Files.copy(Paths.get(inFileStr),Paths.get(outFileStr), StandardCopyOption.REPLACE_EXISTING) to copy the file as your example code does, just likely faster and with only one line of code.

    Otherwise, if you already have opened the two file channels, you can just use
    in.transferTo(0, in.size(), out) to transfer the entire contents of the in channel to the out channel. Note that this method allows to specify a range within the source file that will be transferred to the target channel’s current position (which is initially zero) and that there’s also a method for the opposite way, i.e. out.transferFrom(in, 0, in.size()) to transfer data from the source channel’s current position to an absolute range within the target file.

    Together, they allow almost every imaginable nontrivial bulk transfer in an efficient way without the need to copy the data into a Java side buffer. If that’s not solving your needs, you have to be more specific in your question.

    By the way, you can open a FileChannel directly without the FileInputStream/FileOutputStream detour since Java 7.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题