Domanda

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?

È stato utile?

Soluzione

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.

Altri suggerimenti

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

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top