Signup/Sign In

Java PipedReader close() method

In this tutorial, we will learn about the close() method of the PipedReader class in Java. This method belongs to java.io package, and it is used to close this PipedReader stream and free all system resources linked with the stream.

Syntax

This is the syntax declaration of a close() method, this method does not accept any parameter and does not return any parameter but it may throw an exception at the time of closing the stream.

public void close() throws IOException  

Example: Close PipedReader Instance in Java

In this example, we are demonstrating the use of close() method, when we read the data from the stream we close that stream using the close() method. After calling this all the resources associated with the stream get released and we cannot use stream after this.

import java.io.PipedReader;
import java.io.PipedWriter;
public class StudyTonight 
{
	public static void main(String args[])
	{
		try
		{
			PipedWriter pipedWriter=new PipedWriter();  
			PipedReader pipedReader=new PipedReader(pipedWriter);  
			pipedWriter.write("Hello Studytonight");  
			System.out.println("Closing pipedReader");  
			pipedReader.close();  
			System.out.println("Done!");
		}
		catch(Exception e)
		{
			System.out.println("Error: "+e.toString());
		}
	}
}


Closing pipedReader
Done!

Example: Close PipedReader Instance in Java

In the following program, we are closing the PipedReader before it's used so it will throw an error: java.io.IOException: Pipe closed, because all the resources linked with it are vanished and so it will not work correctly.

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

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


Error: java.io.IOException: Pipe closed

Conclusion

In this tutorial, we learned about the close() method PipedReader class, this method belongs to java.io package, and it is used to close this PipedReader stream and free all system resources linked with the stream.



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.