Hurry! Try our new Interactive Courses for FREE. 🥳   🚀

PipedWriter close() method in Java

In this tutorial, we will learn about the close() method of PipedWriter class in Java. This method belongs to java.io package, and it is used to close this PipedWriter 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 1: Close PipedWriter Instance

In the following example, we have created an object of PipedWriter class and with the help of this class, we created the object of PipedReader class. After the creation of these two objects, we called the close() method on PipedWriter class to free all the resources linked with this stream and it works correctly in this case.

import java.io.IOException;
import java.io.PipedReader;
import java.io.PipedWriter;
class StudyTonight
{
	public static void main(String[] args) throws IOException 
	{ 
		PipedWriter pipedWriter = new PipedWriter();  
		PipedReader pipedReader = new PipedReader(pipedWriter);  
		pipedWriter.close();   
		System.out.println("PipedWriter is closed...");  
	} 
}


PipedWriter is closed...

Example 2: Close PipedWriter Instance

In this example, we are trying to illustrate how it throws an exception when the stream is already closed and we try to write to the stream. Here, we can see that we closed the PipedWriter stream, and then we are trying to write the data and that's why it has thrown an exception with the message "Pipe not connected"

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


Error: java.io.IOException: Pipe not connected

Conclusion

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