OutputStreamWriter write(int) in Java

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

Syntax:

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

This method takes one argument. This method writes a single character.

Parameters: One parameter is required for this method.

c: int specifying a character to be written.

Returns: NA

Throws:

IOException - If an I/O error occurs

Approach 1: When no exception

Java

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;

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

        OutputStream out = new FileOutputStream("D:\\hello.txt");
        OutputStreamWriter outputStreamWriter = new OutputStreamWriter(out);

        int c = 'a';
        outputStreamWriter.write(c);
        System.out.println("Successfully writes");
        outputStreamWriter.close();
    }
}

Output:

Successfully writes


Approach 2: IOException 

Java

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;

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

        OutputStream out = new FileOutputStream("D:\\hello.txt");
        OutputStreamWriter outputStreamWriter =
new OutputStreamWriter(out);

        int c = 'a';
        outputStreamWriter.close();
        outputStreamWriter.write(c);
        System.out.println("Successfully writes");

    }
}

Output:

Exception in thread "main" java.io.IOException: Stream closed at java.base/sun.nio.cs.StreamEncoder.ensureOpen(StreamEncoder.java:51) at java.base/sun.nio.cs.StreamEncoder.write(StreamEncoder.java:124) at java.base/sun.nio.cs.StreamEncoder.write(StreamEncoder.java:119) at java.base/java.io.OutputStreamWriter.write(OutputStreamWriter.java:190) at com.OutputStreamWriter.OutputStreamWriterwrite.main(OutputStreamWriterwrite.java:16)


Some other methods of OutputStreamWriter

close()This method closes the stream, flushing it first.

flush()This method flushes the stream.

getEncoding()This method returns the name of the character encoding being used by this stream.

OutputStreamWriter(OutputStream)This method creates an OutputStreamWriter that uses the default character encoding.

OutputStreamWriter(OutputStream, Charset)This method creates an OutputStreamWriter that uses the given charset.

OutputStreamWriter(OutputStream, CharsetEncoder)This method creates an OutputStreamWriter that uses the given charset encoder.

OutputStreamWriter(OutputStream, String)This method creates an OutputStreamWriter that uses the named charset.

write(int)This method writes a single character.

write(char[], int, int)This method writes a portion of an array of characters.

write(String, int, int)This method writes a portion of a string.

No comments:

Post a Comment