OutputStreamWriter in Java

An OutputStreamWriter is a bridge from character streams to byte streams: Characters written to it are encoded into bytes using a specified charset. The charset that it uses may be specified by name or may be given explicitly, or the platform’s default charset may be accepted.

Each invocation of a write() method causes the encoding converter to be invoked on the given character(s). The resulting bytes are accumulated in a buffer before being written to the underlying output stream. The size of this buffer may be specified, but by default it is large enough for most purposes. Note that the characters passed to the write() methods are not buffered.

For top efficiency, consider wrapping an OutputStreamWriter within a BufferedWriter so as to avoid frequent converter invocations.

Writer writer =new BufferedWriter(new OutputStreamWriter(new FileOutputStream(“/Test/TestFolder/test-file4.txt”), “UTF-8”)

Constructors

OutputStreamWriter in Java

Methods

Screen Shot 2020-04-08 at 6.20.00 PM

package com.java.io;

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

public class OutputStreamWriterExample {

    public static void main(String[] args) {

        FileOutputStream fos = null;
        OutputStreamWriter osw = null;
        String data = "Testing OutputStreamWriter functionality";
        try {
            fos = new FileOutputStream("/Test/TestFolder/test-file4.txt");
            osw = new OutputStreamWriter(fos, "UTF-8");
            osw.write(data);
            osw.flush();
            System.out.println("Data written to File");
        } catch (IOException ioe) {
            ioe.printStackTrace();
        } finally {
            // Closing the streams
            if (fos != null)
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            if (osw != null)
                try {
                    osw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
        }
    }

}
Data written to File
Screen Shot 2020-04-08 at 6.11.57 PM

Leave a Reply

Your email address will not be published. Required fields are marked *