Outputstreamwriter

The OutputStreamWriter class is utilized for converting a character stream into a byte stream by encoding the characters into bytes with a designated charset. When the write method is invoked, the encoding converter transforms the character into bytes, which are stored in a buffer before being sent to the output stream. It is important to note that the characters provided to the write methods are not buffered. To enhance the efficiency of OutputStreamWriter, it is recommended to pair it with a BufferedWriter to minimize the frequency of converter calls.

Constructor

Constructor Description
OutputStreamWriter(OutputStream out) It creates an OutputStreamWriter that uses the default character encoding.
OutputStreamWriter(OutputStream out, Charset cs) It creates an OutputStreamWriter that uses the given charset.
OutputStreamWriter(OutputStream out, CharsetEncoder enc) It creates an OutputStreamWriter that uses the given charset encoder.
OutputStreamWriter(OutputStream out, String charsetName) It creates an OutputStreamWriter that uses the named charset.

Methods

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 anarrayof characters.
void write(int c) It writes a single character.
void write(String str, int off, int len) It writes a portion of astring.

Example

Example

public class OutputStreamWriterExample {
	public static void main(String[] args) {

		try {
			OutputStream outputStream = new FileOutputStream("output.txt");
			Writer outputStreamWriter = new OutputStreamWriter(outputStream);

			outputStreamWriter.write("Hello World");

			outputStreamWriter.close();
		} catch (Exception e) {
			e.getMessage();
		}
	}
}

Output:

Output

output.txt file will contains text  "Hello World"

Input Required

This code uses input(). Please provide values below: