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

PipedReader connect() method in Java

In this tutorial, we will learn about PipedReader in Java. This method is used to cause this PipedReader to be connected to the given PipedWriter (source) when this PipedReader is not previously connected to any of the other PipedWriter.

Syntax:

This is the syntax declaration of the connect method of PipedWriter class which accepts the object of PipedWriter as a source but this method does not return anything.

public void connect(PipedWriter source);

Example: Connect PipReader in Java

In this example, we will learn about how the connect() method works, we use this method to connect the PipedWriter with the PipedReader in another way we can say this method causes this piped reader to be connected to the piped writer src.

import java.io.PipedReader;
import java.io.PipedWriter;
public class StudyTonight 
{
	public static void main(String args[])
	{
		try
		{
			PipedReader reader = new PipedReader(); 
			PipedWriter writer = new PipedWriter(); 
			reader.connect(writer); 
			
			writer.write(72); 
			System.out.println((char)reader.read()); 
			writer.write(69); 
			System.out.println((char)reader.read()); 
			writer.write(76); 
			System.out.println( (char)reader.read());   
			writer.write(76); 
			System.out.println( (char)reader.read());   
			writer.write(79); 
			System.out.println( (char)reader.read());   
		}
		catch(Exception e)
		{
			System.out.println("Error: "+e.toString());
		}
	}
}

H E L L O

Example: Connect PipReader in Java

Here, we are implementing the connect method of PipedReader class, we use this method to connect the PipedWriter with the PipedReader. In another way, we can say this method causes this piped reader to be connected to the piped writer src.

import java.io.PipedReader;
import java.io.PipedWriter;
public class StudyTonight 
{
	public static void main(String args[])
	{
		try
		{
			PipedReader reader = new PipedReader(); 
			PipedWriter writer = new PipedWriter(); 
			reader.connect(writer); 
			char[] arr = {'H', 'E', 'L', 'L', 'O'}; 
			writer.write(arr, 0, 5); 
			while(true) 
			{ 
				System.out.print((char) reader.read());           
			} 
		}
		catch(Exception e)
		{
			System.out.println("Error: "+e.toString());
		}
	}
}

HELLO

Conclusion

In this tutorial, we learned about the connect() method of PipedReader class, This method is used to cause this PipedReader to be connected to the given PipedWriter (source) when this PipedReader is not previously connected to any of the other PipedWriter.