writer.flush() : is it always needed?

Hi everybody,

This is just a general IO question. When I learned Java, I was taught that when you use a FileWriter or BufferedWriter, it's good practice to call writer.flush() after writing any line. Is this true, or is that a waste of time? I'm just curious.

Thanks,

Jezzica85

[304 byte] By [jezzica85a] at [2007-11-27 10:18:26]
# 1

> Hi everybody,

> This is just a general IO question. When I learned

> Java, I was taught that when you use a FileWriter or

> BufferedWriter, it's good practice to call

> writer.flush() after writing any line. Is this true,

> or is that a waste of time? I'm just curious.

>

> Thanks,

> Jezzica85

Flush will commit the data you have written to your disk. Sort of like close() but leaves the stream open.

deAppela at 2007-7-28 16:28:47 > top of Java-index,Java Essentials,Java Programming...
# 2

Thank you deAppel,

I did know that about writer.flush(), what I meant by the question is, would it be more efficient to call writer.flush() less, and somehow monitor the size of the buffer, or doesn't it matter how many times you call writer.flush()?

Jezzica85

jezzica85a at 2007-7-28 16:28:47 > top of Java-index,Java Essentials,Java Programming...
# 3

If you are concerned about losing output when your Java program crashes,

you can flush the output buffers. The reason flushing is not automatic

is that it is more efficient to minimize the number of calls to the underlying

file system's write operation -- buffered steams wait and flush themselves

when the buffer is full. Also see PrintWriter's auto flush property.

BigDaddyLoveHandlesa at 2007-7-28 16:28:47 > top of Java-index,Java Essentials,Java Programming...
# 4

Thanks, I didn't know that about buffered streams. I guess I won't worry about flushing them then.

Jezzica85

jezzica85a at 2007-7-28 16:28:47 > top of Java-index,Java Essentials,Java Programming...
# 5

> Thanks, I didn't know that about buffered streams. I

> guess I won't worry about flushing them then.

What one does have to remember is to close them, because close calls flush. A common error people see is when they run a short program that writes a small amount of text to a file. After the program runs they find the file is empty -- they forgot to close.

BigDaddyLoveHandlesa at 2007-7-28 16:28:47 > top of Java-index,Java Essentials,Java Programming...