Bufferedwriter works, but file empty?

前端 未结 4 699
忘掉有多难
忘掉有多难 2020-12-11 08:58

I have the following code:

CSVmaker(LinkedList data) {
    String [] myLines = makeStrings(data);
  //  for (int k = 0; k

        
相关标签:
4条回答
  • 2020-12-11 09:42

    Though the question is answered . I would like to add how buffer works.

    whenever you try to write to a file using buffer,whatever you write gets added to the buffer. When the buffer is full the contents are written to the file . This way we are reducing the number of hits to the hard-drive hence improving the efficency.

    If we want to forcefully write to a file without the buffer getting full , we use flush() method.

    0 讨论(0)
  • 2020-12-11 09:47

    Starting with Java 8, one would simply do it with a try with resources, which automatically closes the BufferedWriter. Also see the usage of the new class Files

    try (BufferedWriter writer = Files.newBufferedWriter(somePath, yourCharset)){
        writer.write(output);
    }
    
    0 讨论(0)
  • 2020-12-11 09:48

    You have to close() the stream after use.
    Call buff.close() after write loop; BufferedWriter will flush data to file at close.

    0 讨论(0)
  • 2020-12-11 09:49

    You never flush the buffer, or close the BufferedWriter.

    After the for loop, make the following calls:

    buff.flush();
    buff.close();
    

    Even with other resources, closing them when done is a good idea.

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