Why is BufferedWriter not writing to file?

2019-07-06 21:37发布

I have this code:

    String[] strings = {"Hi" , "You", "He", "They", "Tetrabenzene", "Caaorine", "Calorine"};

    File file = new File("G:\\words.txt");
    FileWriter fWriter;
    BufferedWriter bWriter;

    try {
        if((file.exists())) {
            file.createNewFile();
        }
        fWriter = new FileWriter(file.getAbsoluteFile(), true);
        bWriter = new BufferedWriter(fWriter);

        //Convert Result objects to JSON and write to file
        for(int j = 0; j < strings.length; ++j) {
            bWriter.write(strings[j]);
                bWriter.newLine();
                System.out.println("done");
        }
    }
    catch(IOException e) {e.printStackTrace();}

I have pretty much the same code 2 or 3 times before this and BufferedWriter is writing perfectly. But for some reason when I get to this code it doesn't write. I've been looking for things that might be wrong but I can't change something and test it quickly as the program takes 10 minutes just to get to this part.

Also, the program prints "done" to the console so I know it is going into the for loop.

Any ideas as to what I'm doing wrong?

2条回答
【Aperson】
2楼-- · 2019-07-06 22:06

Call bWriter.flush() when you want your data to actually be flushed to your file on disk. Or just call bWriter.close() when you're done working with your writer. The bWriter.close() call will call bWriter.flush() internally.

查看更多
Deceive 欺骗
3楼-- · 2019-07-06 22:18

I assume you wanted to add if(!file.exists()) rather than if((file.exists())).

查看更多
登录 后发表回答