Flushing the BufferedWriter Stream in Java

When data is being written using BufferedWriter, unless the total data is an exact multiple of the buffer size, some data will be left in the buffer that has not been written to the destination. Normally, this is not a problem because as soon as the BufferedWriter stream is closed, either explicitly or implicitly when the program terminates, the buffer is implicitly flushed, that is, the remaining buffer contents are written to the destination.

However, there may be occasions when we want to explicitly flush the buffer. To do this, use the java.io.BufferedWriter.flush method. For example, in the WriteBufFile example of the previous section, we add the statement

WriteBufFile

import java.io.*;

public class WriteBufFile
{

public static void main(String[] args) throws
IOException
{
String text;
int i;

FileWriter out = new FileWriter(''File1.txt");
BufferedWriter outBuffer = new BufferedWriter(out);
for (i = 1; i < 11; i++)
{

text = ''Line " + i + " of text\n";
outBuffer.write(text);
outBuffer.flush();
}
outBuffer.close();
out.close();
}
}



immediately before closing the BufferedWriter stream (line 17) to explicitly flush the buffer.

No comments:

Post a Comment