why is bufferedwriter not writing in the file?

久未见 提交于 2019-11-29 14:26:32
  • You are creating the FileWritter inside the loop so you will always truncate the file in each cycle.
  • You forgot to close / flush the writter
  • But with some luck (terminating the program may cause the writter to flush) the file would contain the last word of your input file which I can only guess would be a new line and you probably missed when you opened up the file to check the content.

Your inner loop should be something like this:

try (BufferedWriter bw = new BufferedWriter(new FileWriter("file.txt"))) {
    while (st.hasMoreTokens()) {
        bw.write(st.nextToken());
        bw.newLine();
    }
}

A couple of things:

  1. You're creating a new FileWriter each time through the loop, which will truncate the file each time.
  2. BufferedWriter is buffered, and you're never flushing the buffer. You need to either call bw.flush(), or even better, close the writer when done.
dhruven1600

Ideally you should use following Constructor to create FileWriter,

bw = new BufferedWriter(new FileWriter("files/file.txt",true));

Second parameter, true is for appending the new data. FileWriter will not truncate your previous write.

and your reader will be able to read proper data.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!