Signup/Sign In

Java PipedWriter write() Method

In this tutorial, we will learn about write() method of PipedWriter class in Java. This method is used to write the data to the output piped stream.

Syntax

This is the syntax declaration of the write() method this does not return anything as its return type is void.

public void write(char[] cbuf, int off, int len)

Example: PipedWriter write() Method

In this example, the write() method writes a specified character to the PipedWriter. Also, we have another overloading method write(char[] arr, int offset, int maxlen), In this method, arr is the source array, offset is the index from where it will start writing, and maxlen is the length of the string is to be written.

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

Example 2: PipedWriter write() Method

Here in this example, we are implementing the write() method of PipedWriter class to write the data. Firstly we created objects of PipedWriter class and PipedReader class, then using the connect() method we connected both the methods. Now we are writing the characters to the PipedWriter and again reading using PipedReader.

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

Conclusion

In this tutorial, we learned about the write() method of PipedWritter class. This method comes with the two overloading methods and It writes len characters from the specified character array starting at offset off to this piped output 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.