I'm trying to write billions of strings lines to a file, it works for up to 40 million lines, but it's throwing out "java.nio.BufferOverflowException" error for 400 million lines. I also think my solution is slow as it takes 45 seconds to write 40 million lines. Below is the code.
public static void main(String[] args) throws FileNotFoundException, IOException {
byte[] buffer = "Help I am trapped in a fortune cookie factory\n".getBytes();
int number_of_lines = 400000000;
FileChannel rwChannel = new RandomAccessFile("textfile.txt", "rw").getChannel();
ByteBuffer wrBuf = rwChannel.map(FileChannel.MapMode.READ_WRITE, 0, buffer.length * number_of_lines);
for (int i = 0; i < number_of_lines; i++) {
wrBuf.put(buffer);
}
rwChannel.close();
}
How can I make it be faster if possible and also write more than 2 billion lines of string?
size
"must be non-negative and no greater thanInteger.MAX_VALUE
". Do you specifically want memory-mapped I/O, or could you just useRandomAccessFile.write
? \$\endgroup\$