PipedOutputStream write(int) in Java

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

Syntax:

void java.io.PipedOutputStream.write(int b) throws IOException

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

Implements the write method of OutputStream.

Parameters: One parameter is required for this method.

b: the byte to be written.

Returns: NA

Throws:

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

Approach 1: When no exception

Java

import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;

public class PipedOutputStreamwrite {
    public static void main(String[] args) throws IOException {
        PipedOutputStream pipedOutputStream = new PipedOutputStream();

        PipedInputStream pipedInputStream =
new PipedInputStream();
        pipedOutputStream.connect(pipedInputStream);
        int b = 'a';
        pipedOutputStream.write(b);

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

    }
}

Output:

Successfully writes


Approach 2: IOException 

Java

package com.PipedOutputStream;

import java.io.IOException;
import java.io.PipedOutputStream;

public class PipedOutputStreamwrite {
    public static void main(String[] args) throws IOException {
        PipedOutputStream pipedOutputStream =
new PipedOutputStream();

        int b = 'a';
        pipedOutputStream.write(b);

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

    }
}

Output:

Exception in thread "main" java.io.IOException: Pipe not connected at java.base/java.io.PipedOutputStream.write(PipedOutputStream.java:119) at com.PipedOutputStream.PipedOutputStreamwrite.main(PipedOutputStreamwrite.java:11)


Some other methods of PipedOutputStream

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

connect(PipedInputStream)This method connects this piped output stream to a receiver.

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

PipedOutputStream()This method creates a piped output stream that is not yet connected to a piped input stream.

PipedOutputStream(PipedInputStream)This method creates a piped output stream connected to the specified piped input stream.

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

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

No comments:

Post a Comment