bufferedwriter stops in the middle of writing

前端 未结 4 734
长情又很酷
长情又很酷 2021-01-18 02:39

For some reason this code results in a truncated text.txt file. It should (according to me) write out 1000 results, but the output file has various amounts of lines (dependi

4条回答
  •  轮回少年
    2021-01-18 03:01

    Two things.

    1. Flush the stream
    2. Close the stream

    Try something like:

     Writer out = null;
     try {
        out = new BufferedWriter(new FileWriter("test.txt"),16*1024);
    
        // Write some stuff
    
        out.flush();
     } finally {
        try {
            out.close();
        } catch (Exception exp) {
        }
    }
    

    Try and remember, it's a "buffer". That means that it's keeping stuff stored in memory until it decides it needs to be written or your explicitly ask it to "flush" it's contents.

    Also, you should always close your streams. This prevents possible locked file issues and file handle issues :P

提交回复
热议问题