gurehbgui
gurehbgui

Reputation: 14684

writing to a file, but not just at the end

I want to write something to a file line by line. I have the problem, that this process takes a lot of time and get canceld sometimes. The current version write the stuff to the file just at the end. Is it possible to write it to the file line by line?

E.g. if I abboard after line 4 (of 400) the file currently is empty. But I want to have the 4 line already in the file.

Here is my code:

String path = args[0];
String filename = args[1];

BufferedReader bufRdr = // this does not matter

BufferedWriter out = null;
FileWriter fstream;
try {
    fstream = new FileWriter(path + "Temp_" + filename);
    out = new BufferedWriter(fstream);
} catch (IOException e) {
    System.out.println(e.toString());
}

String line = null;

try {
    while ((line = bufRdr.readLine()) != null) {            
        // HERE I'm doing the writing with out.write
        out.write(...);
    }
} catch (IOException e) {
    System.out.println(e.toString());
}

try {
    out.close();
} catch (IOException e) {
    System.out.println(e.toString());
}

Upvotes: 2

Views: 339

Answers (5)

lahiru
lahiru

Reputation: 21

The data you write to the buffer normally will not actually be written until out.flush() or out.close() is closed. so for your requirement you should use out.flush();

Upvotes: 1

pulasthi
pulasthi

Reputation: 1750

Use the flush function when you want to make sure the data that is already been written to the writer gets into the file

out.flush()

Upvotes: 5

abletterer
abletterer

Reputation: 109

Considering the java documentation FileWriter, you can directly write things to a file using the FileWriter, without using a BufferedWriter.

Also, as pointed out, you need to flush your datas before closing your buffer. The function write only fill your buffer, but it doesn't write to the file on the disk. This operation is done by using flush or close (to write the current content of the buffer to the disk). The difference between these two functions is that flush let's you write things after and close closes the stream definitely.

Upvotes: 2

Amir Kost
Amir Kost

Reputation: 2168

Use out.flush() after calling out.write(...).

Upvotes: 2

Thihara
Thihara

Reputation: 6969

Try out.flush() after out.write(...)

Upvotes: 3

Related Questions