BufferedOutputStream flush() method in Java with Examples
The flush() method of BufferedOutputStream class in Java is used to flush the buffered output stream. This method is used to compel the bytes of buffered output to be written out to the main output stream.
Syntax:
public void flush()
throws IOException
Specified By: This method is specified by the flush() method in Flushable interface.
Overrides: This method overrides the flush() method in FilterOutputStream class.
Parameters: This method does not accept any parameter.
Return value: This method does not return any value.
Exception: This method throws IOException if an I/O error occurs.
Below programs illustrate flush() method in BufferedOutputStream class in IO package:
Program 1:
import java.io.*;
public class GFG {
public static void main(String[] args) throws Exception
{
ByteArrayOutputStream
byteArrayOutStr
= new ByteArrayOutputStream();
BufferedOutputStream buffOutputStr
= new BufferedOutputStream(
byteArrayOutStr);
byte b[] = { 71 , 69 , 69 , 75 , 83 };
buffOutputStr.write(b);
buffOutputStr.flush();
for ( byte by : byteArrayOutStr
.toByteArray()) {
char ch = ( char )by;
System.out.print(ch);
}
}
}
|
Program 2:
import java.io.*;
public class GFG {
public static void main(String[] args) throws Exception
{
ByteArrayOutputStream byteArrayOutStr = new ByteArrayOutputStream();
BufferedOutputStream buffOutputStr
= new BufferedOutputStream(
byteArrayOutStr);
byte b1[] = { 71 , 69 , 69 , 75 , 83 };
buffOutputStr.write(b1);
buffOutputStr.flush();
byte b2[] = { 70 , 79 , 82 };
buffOutputStr.write(b2);
buffOutputStr.flush();
buffOutputStr.write(b1);
buffOutputStr.flush();
for ( byte by : byteArrayOutStr.toByteArray()) {
char ch = ( char )by;
System.out.print(ch);
}
}
}
|
References:
https://docs.oracle.com/javase/10/docs/api/java/io/BufferedOutputStream.html#flush()
Last Updated :
28 May, 2020
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...