FilterOutputStream write(int) in Java

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

Syntax:

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

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

The write method of FilterOutputStreamcalls the write method of its underlying output stream, that is, it performs out.write(b).

Implements the abstract write method of OutputStream.

Parameters: One parameter is required for this method.

b: the byte.

Returns: NA

Throws:

IOException - if an I/O error occurs.

Approach 1: When no Exception

Java

import java.io.File;
import java.io.FileOutputStream;
import java.io.FilterOutputStream;
import java.io.IOException;

public class FilterOutputStreamwrite2 {
    public static void main(String[] args) throws IOException {
        File data = new File("D:\\hello.txt");
        FileOutputStream file = new FileOutputStream(data);
        FilterOutputStream filter = new FilterOutputStream(file);

        int b = 'A';
        filter.write(b);
        System.out.println("Successfully write into the filter output stream");
        filter.close();
    }
}

Output:

Successfully write into the filter output stream


hello.txt file contains the below data.

A


Approach 2: IOException 

Java

import java.io.File;
import java.io.FileOutputStream;
import java.io.FilterOutputStream;
import java.io.IOException;

public class FilterOutputStreamwrite2 {
    public static void main(String[] args) throws IOException {
        File data = new File("D:\\hello.txt");
        FileOutputStream file = new FileOutputStream(data);
        FilterOutputStream filter = new FilterOutputStream(file);

        int b = 'A';
        filter.close();

        filter.write(b);
        System.out.println("Successfully write into the filter output stream");
        filter.close();
    }
}

Output:

Exception in thread "main" java.io.IOException: Stream Closed at java.base/java.io.FileOutputStream.write(Native Method) at java.base/java.io.FileOutputStream.write(FileOutputStream.java:311) at java.base/java.io.FilterOutputStream.write(FilterOutputStream.java:87)


Some other methods of FilterOutputStream

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

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

write(byte[])This method writes b.length bytes to this output stream.

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


No comments:

Post a Comment