Signup/Sign In

PipedWriter flush() Method in Java

In this tutorial, we will learn about the flush() method of PipedWriter class in Java. This method is available in the java.io package. This method is used to flush this PipedWriter stream and forces characters to be written out of any buffered output. It is a non-static method, it is accessible with the class object only and if we try to access the method with the class name then we will get an error.

Syntax

This is the syntax declaration of the flush() method, this method does not accept any parameter and does not return anything since its return type is void.

 public void flush();

Example 1

In this example, we created the objects of the PipedWriter and PipedReader class and after that, we write the data, and then we have connected the reader and writer using connect() method. to flush out the stream we call the flush() method.

import java.io.IOException;
import java.io.PipedReader;
import java.io.PipedWriter;
class StudyTonight
{
	public static void main(String[] args) throws IOException 
	{ 
		PipedWriter writer = new PipedWriter();
		PipedReader reader = new PipedReader();

		try 
		{
			writer.connect(reader);
			writer.write(65);
			writer.flush();
			System.out.println("Writer flushed.");
			
			for (int i = 0; i < 2; i++) 
			{
				System.out.println("" + (char) reader.read());
			}
		} 
		catch (IOException ex) 
		{
			ex.printStackTrace();
		}
	} 
}


Writer flushed.
A

Example 1

In this example, we are implementing the flush() method to flush the given PipedWriter stream and force characters to be written out of any buffered output.

import java.io.IOException;
import java.io.PipedReader;
import java.io.PipedWriter;
class StudyTonight
{
	public static void main(String[] args) throws IOException 
	{ 
		int val = 65;
		try 
		{
			PipedWriter pipedWriter = new PipedWriter();
			PipedReader pipedReader = new PipedReader();

			pipedWriter.connect(pipedReader);

			for (int i = 0; i < 3; ++i) 
			{
				pipedWriter.write(val);
				val++;
			}

			pipedWriter.flush();

			for (int i = 0; i < 3; ++i) 
			{			
				char ch = (char) pipedReader.read();
				System.out.print("" + ch);
			}

			pipedWriter.close();
			pipedWriter.close();
		} 
		catch (Exception e) 
		{
			System.out.println("Error: "+e.toString());
		}
	} 
}


ABC

Conclusion:

In this tutorial, we learned about the flush() method, This method is used to flush this PipedWriter stream and forces characters to be written out of any buffered output.



About the author:
I am the founder of Studytonight. I like writing content about C/C++, DBMS, Java, Docker, general How-tos, Linux, PHP, Java, Go lang, Cloud, and Web development. I have 10 years of diverse experience in software development.