OutputStreamWriter to the console Tutorial

The OutputStreamWriter class can serve multiple purposes, but primarily it is used to convert character streams to byte streams. This tutorial is practically the exact opposite of my InputStreamReader Tutorial, I highly recommend watching it first. OutputStreamWriter has several overloaded constructors with each taking an OutputStream (like System.out, or FileOutputStream) as the first parameter. This tutorial will utilize the constructor that only takes a single parameter. The OutputStreamWriter class implements AutoClosable so we can use the try-with-resources type exception handling. There are only four public methods in the OutputStreamWriter class: close(), flush(), getEncoding(), and write(). The close() method will be handled by our try-with-resources syntax, we'll ignore the flush() and getEncoding() for now, and the write() method has three overloaded versions.



Open the command prompt (CMD - see the Getting Started ) and type in the following commands.

C:\Windows\System32>cd \
C:\>md Java
C:\>cd Java
C:\Java>
C:\Java>md OSW
C:\Java>cd OSW
C:\Java\OSW>Notepad OSW.java

Copy and Paste, or type the following code into Notepad and be sure to save the file when you are done.


import java.io.*;
class OSW {
    public static void main(String args[]) {
        try (OutputStreamWriter OSW = new OutputStreamWriter(System.out)) {
            OSW.write("Hello World\n");
            OSW.write(97);
            OSW.write(98);
            OSW.write(99);
            OSW.write(49);
            OSW.write(50);
            OSW.write(51);
            OSW.write(10);
            OSW.write('A');
            OSW.write('B');
            OSW.write('C');
            OSW.write('1');
            OSW.write('2');
            OSW.write('3');
            OSW.write('\n');
            char cArray[] = "Hello World".toCharArray();
            OSW.write(cArray);
        } catch(IOException e) {
            System.out.println(e.getMessage());
        }
    }
}

Now switch back to the command prompt (CMD) and type in javac OSW.java and press Enter.
Now type in java OSW and press Enter.


C:\Java\OSW>javac OSW.java
C:\Java\OSW>java OSW
Hello World
abc123
ABC123
Hello World


Final thoughts

This simple tutorial demonstrates writing the output stream to the standard output which by default is the console. Once I have completed my tutorial on the File class I will demonstrate using OutputStreamWriter to a file.


Tutorials