The OutputStreamWriter class in Java is used to convert a character stream into a byte stream using a specified character encoding.
In this chapter, we will learn what the OutputStreamWriter class is, why it is used, its declaration, constructors, important methods, and how to write character data to byte streams using examples.
The OutputStreamWriter class acts as a bridge between character streams and byte streams, and it is used to encode characters into bytes using a specified charset.
When the write() method is called, characters are converted into bytes using an encoding converter and then written to the underlying output stream. To improve performance and avoid frequent encoding operations, OutputStreamWriter is commonly used with BufferedWriter.
The following declaration shows how the OutputStreamWriter class is defined:
The OutputStreamWriter class provides constructors to create a writer with different character encodings.
This constructor creates an OutputStreamWriter that uses the default character encoding.
Syntax:
Here is the syntax:
This constructor creates an OutputStreamWriter that uses the specified charset.
Syntax:
Here is the syntax:
This constructor creates an OutputStreamWriter that uses the specified charset encoder.
Syntax:
Here is the syntax:
This constructor creates an OutputStreamWriter that uses the named charset.
Syntax:
Here is the syntax:
The following code shows how the constructors of the OutputStreamWriter class are used.
The OutputStreamWriter class provides the following methods to write encoded character data.
| Modifier and Type | Method | Description |
|---|---|---|
| void | close() | It closes the stream, flushing it first. |
| void | flush() | It flushes the stream. |
| String | getEncoding() | It returns the name of the character encoding being used by this stream. |
| void | write(char[] cbuf, int off, int len) | It writes a portion of an array of characters. |
| void | write(int c) | It writes a single character. |
| void | write(String str, int off, int len) | It writes a portion of a string. |
The following examples demonstrate how to use the Java OutputStreamWriter class.
The following example demonstrates how to write character data to a file using the OutputStreamWriter class.
Output:
Hello World
The following example demonstrates how to write text using a specific character encoding with the OutputStreamWriter class.
Output:
Java I/O – UTF-8 Example
We request you to subscribe our newsletter for upcoming updates.