1

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?

3 Answers3

3

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

Thomas
  • 11,272
  • 2
  • 24
  • 40
3

Close the BufferedWriter object.

writer.close();

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

Prasad
  • 1,188
  • 3
  • 11
  • 29
  • Is there a reason that without the close, it only writes it partially? – Useablelobster Oct 17 '13 at 13:11
  • 1
    The concept of the BufferedWrite is to buffer. It flushes when the buffer is full and reduces the number of separate IO opertions. It also flushes when you call flush and when you close the writer. – Thomas Oct 17 '13 at 13:15
  • 1
    Yes surely there is a reason. It closes the current stream with which you are writing a file. It needs to be closed, in order to reflect the changes that you have made in a file. It also flushes the stream. – Prasad Oct 17 '13 at 13:15
  • @Useablelobster you haven't accepted anybody's answer. – Prasad Oct 18 '13 at 06:44
2

Also write writer.flush() after writing to file

writer.close() is also a good choice
AJ.
  • 4,526
  • 5
  • 29
  • 41
  • 2
    calling `close()` should be enough, see http://docs.oracle.com/javase/7/docs/api/java/io/BufferedWriter.html#close%28%29 – divadpoc Oct 17 '13 at 13:12