Pipedwriter - Java Tutorial

Pipedwriter

BLUF: Mastering Pipedwriter is a key requirement for any Java developer. This lesson breaks down the object-oriented principles and syntax required to use this concept in real-world applications.
Write Once, Run Anywhere Tip: Pipedwriter

Java's versatility is unmatched. Learn how Pipedwriter fits into the Java ecosystem and improves your code structure in the tutorial below.

The PipedWriter class in Java is employed to write characters to a pipe as a character stream. It is primarily used for writing text content. Typically, PipedWriter is linked to a PipedReader and can be utilized by multiple threads simultaneously.

Constructor

Constructor Description
PipedWriter() It creates a piped writer that is not yet connected to a piped reader.
PipedWriter(PipedReader snk) It creates a piped writer connected to the specified piped reader.

Method

Modifier and Type Method Method
void close() It closes this piped output stream and releases any system resources associated with this stream.
void connect(PipedReader snk) It connects this piped writer to a receiver.
void flush() It flushes this output stream and forces any buffered output characters to be written out.
void write(char[] cbuf, int off, int len) It writes len characters from the specified characterarraystarting at offset off to this piped output stream.
void write(int c) It writes the specified char to the piped output stream.

Example

Example

import java.io.PipedReader;
import java.io.PipedWriter;

public class PipeReaderExample2 {
	public static void main(String[] args) {
		try {

			final PipedReader read = new PipedReader();
			final PipedWriter write = new PipedWriter(read);

			Thread readerThread = new Thread(new Runnable() {
				public void run() {
					try {
						int data = read.read();
						while (data != -1) {
							System.out.print((char) data);
							data = read.read();
						}
					} catch (Exception ex) {
					}
				}
			});

			Thread writerThread = new Thread(new Runnable() {
				public void run() {
					try {
						write.write("I love my country\n".toCharArray());
					} catch (Exception ex) {
					}
				}
			});

			readerThread.start();
			writerThread.start();

		} catch (Exception ex) {
			System.out.println(ex.getMessage());
		}

	}
}

Output:

Output

I love my country

Input Required

This code uses input(). Please provide values below:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience