How to use Java OutputStreamWriter?

OutputStreamWriter is a conversion stream used in Java to write characters into byte streams. It can convert character streams into byte stream output.

Below is a basic example of how to use OutputStreamWriter:

  1. Create an OutputStream object for writing bytes, such as a FileOutputStream.
OutputStream outputStream = new FileOutputStream("output.txt");
  1. Create an OutputStreamWriter object and pass a byte output stream as a parameter to it.
OutputStreamWriter writer = new OutputStreamWriter(outputStream);
  1. Use the write method of the writer object to write characters to the byte output stream.
writer.write("Hello World!");
  1. Finally, use the flush method of the writer object to write the characters from the buffer into the byte output stream, and then close the writer object.
writer.flush();
writer.close();

Here is the complete example code:

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

public class Main {
    public static void main(String[] args) {
        try {
            OutputStream outputStream = new FileOutputStream("output.txt");
            OutputStreamWriter writer = new OutputStreamWriter(outputStream);
            writer.write("Hello World!");
            writer.flush();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

The above code writes the string “Hello World!” to the file output.txt.

Please note that OutputStreamWriter also allows specifying character encoding, for example:

OutputStreamWriter writer = new OutputStreamWriter(outputStream, "UTF-8");

This ensures writing to the byte stream in the specified character encoding.

Leave a Reply 0

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


广告
Closing in 10 seconds
bannerAds