写入数十亿行时如何解决BufferOverflow异常错误?

时间:2019-05-09 17:08:33

标签: java file buffer streamwriter buffer-overflow

我试图将数十亿个字符串行写入文件,但它抛出了“ java.nio.BufferOverflowException”错误。我还认为我的解决方案很慢,因为它需要45秒才能写入4000万行。下面是代码。

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

如果可能的话,我该如何使其更快并且还要写入超过20亿行的字符串?

0 个答案:

没有答案