PipedWriter write(int) in Java

write(int): This method is available in the java.io.PipedWriter class of Java.

Syntax:

void java.io.PipedWriter.write(int c) throws IOException

This method takes one argument. This method writes the specified char to the piped output stream.

If a thread was reading data characters from the connected piped input stream, but the thread is no longer alive, then an IOException is thrown.

Note:

It implements the write method of the Writer.

Parameters: One parameter is required for this method.

c: the char to be written.

Returns: NA

Throws:

IOException - if the pipe is broken, unconnected, closed or an I/O error occurs.

Approach 1: When no exception

Java

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

public class PipedWriterwrite {
    public static void main(String[] args) throws IOException {

        PipedWriter pipedWriter = new PipedWriter();

        PipedReader pipedReader =new PipedReader();
        pipedWriter.connect(pipedReader);
        int c = 'a';
        pipedWriter.write(c);

        System.out.println("Successfully writes");
        pipedWriter.close();

    }
}

Output:

Successfully writes


Approach 2: IOException

Java

package com.PipedWriter;

import java.io.IOException;
import java.io.PipedWriter;

public class PipedWriterwrite {
    public static void main(String[] args) throws IOException {

        PipedWriter pipedWriter = new PipedWriter();

        int c = 'a';
        pipedWriter.write(c);

        System.out.println("Successfully writes");
        pipedWriter.close();

    }
}

Output:

Exception in thread "main" java.io.IOException: Pipe not connected at java.base/java.io.PipedWriter.write(PipedWriter.java:122) at com.PipedWriter.PipedWriterwrite.main(PipedWriterwrite.java:12)


Some other methods of PipedWriter

close()This method closes this piped output stream and releases any system resources associated with this stream.

connect(PipedReader)This method connects this piped writer to a receiver.

flush()This method flushes this output stream and forces any buffered output characters to be written out.

PipedWriter(): This method creates a piped writer that is not yet connected to a piped reader.

PipedWriter(PipedReader)This method creates a piped writer connected to the specified piped reader.

write(int)This method writes the specified char to the piped output stream.

write(char[], int, int)This method writes len characters from the specified character array starting at offset off to this piped output stream.

No comments:

Post a Comment