📜  Java I/O-OutputStreamWriter

📅  最后修改于: 2020-09-27 07:19:50             🧑  作者: Mango

Java OutputStreamWriter

OutputStreamWriter是一个类,用于将字符流转换为字节流,使用指定的字符集将字符编码为字节。 write()方法调用编码转换器,该转换器将字符转换为字节。然后将生成的字节存储在缓冲区中,然后再写入基础输出流。传递给write()方法的字符不被缓冲。我们通过在BufferedWriter中使用OutputStreamWriter来优化其性能,以避免频繁的转换器调用。

建设者

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.

方法

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.

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();
}
}
}

输出: