Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is BufferedWriter not writing to file?

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?

like image 839
user3210944 Avatar asked Dec 27 '25 15:12

user3210944


1 Answers

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.

like image 188
peter.petrov Avatar answered Dec 31 '25 18:12

peter.petrov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!