3

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?

tshepang
  • 12,111
  • 21
  • 91
  • 136
user3210944
  • 57
  • 1
  • 6
  • 1
    Close your writers at the end. `bWriter.close(); fWriter.close();` – Alexis C. Jan 18 '14 at 22:29
  • For others who might have a related issue. I had the close statement in the finally block and the BufferedWriter didnt work. When I put the close statement back in the try block it worked again. – wenzel267 Dec 13 '18 at 06:58

2 Answers2

8

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.

peter.petrov
  • 38,363
  • 16
  • 94
  • 159
0

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