esxuwaca
esxuwaca

Reputation: 21

How can i write in a Java File?

I want to write in a File but i am having a very extrange problem. If i write the code like this:

BufferedWriter bw = new BufferedWriter(new FileWriter(nom + ".txt"));
        String s = "";
        for (int i = 0; i < DIMENSIO; i++) {
            for (int j = 0; j < DIMENSIO; j++) {
                s +=tauler.isBomba(i,j);
                s += '\n';
                s +=tauler.isSeleccionat(i,j);
                s += '\n';
            }
        }
        bw.write(s);

The file is empty, but if I write the code in this way:

BufferedWriter bw = new BufferedWriter(new FileWriter(nom + ".txt"));
        String s = "";
        for (int i = 0; i < DIMENSIO; i++) {
            for (int j = 0; j < DIMENSIO; j++) {
                s +=tauler.isBomba(i,j);
                s += '\n';
                s +=tauler.isSeleccionat(i,j);
                s += '\n';
                bw.write(s);
            }
        }

It works. The problem is that in the second way it's not correct cause i need to write it after the for.

Upvotes: 1

Views: 63

Answers (2)

dcp
dcp

Reputation: 55444

You need to close the BufferedWriter object at the end.

bw.close();

That causes the data to get flushed out of the stream to the file. I think the reason it works when it's inside the loop is that it is flushing the data periodically.

But a better way to write this, as suggested by Clashsoft, is to use a try-with-resource statement instead, which will handle closing the BufferedWriter automatically.

try(BufferedWriter writer = new BufferedWriter(new FileWriter(fileName))) {
    // do your logic here
    writer.write(str);

    // once control leaves this block, the writer gets closed automatically
}
catch(IOException e){
    // handle the exception
}

Upvotes: 4

Lucas Diehl
Lucas Diehl

Reputation: 47

Try to use bw.close() after you call bw.write(s);

Upvotes: 0

Related Questions