I'm trying to write elements from an ArrayList to a text document. My bufferedwriter code is as follows (with the actual filepath):

Path file = Paths.get("(filepath)");
    BufferedWriter writer = Files.newBufferedWriter(file, Charset.forName("US-ASCII"));
    for (int j = 0; j < 100000; j++) {
        writer.write(Integer.toString(radicalsAndPositions.get(j).get(0)) + "," + Integer.toString(radicalsAndPositions.get(j).get(1)) + " , " + "\n");
    }

The arraylist is full up to the 100,000th element, and it generates a file, but misses values from the end. When I restrict 'j' to 10,000, I only get the first 9170 lines generated. With the full 100,000, I only get the first 99250 lines.

Restricting 'j' to 1000 gives me an empty file.

The document is generating correctly, with the correct elements, it is just ending prematurely. Why is this, and how can I fix it?

有帮助吗?

解决方案

Close the BufferedWriter object.

writer.close();

It will not write your file unless you close an object of BufferedWriter.

其他提示

Close the buffered writer when you are done to make sure the buffer is flushed.

Also write writer.flush() after writing to file

writer.close() is also a good choice
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top