OutputStreamWriter是Java中用于将字符写入字节流的转换流。它可以将字符流转换为字节流输出。
下面是OutputStreamWriter的基本使用示例:
OutputStream outputStream = new FileOutputStream("output.txt");
OutputStreamWriter writer = new OutputStreamWriter(outputStream);
writer.write("Hello World!");
writer.flush();
writer.close();
完整示例代码如下:
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();
}
}
}
上述代码将字符串"Hello World!"写入output.txt文件中。
请注意,OutputStreamWriter还可以指定字符编码,例如:
OutputStreamWriter writer = new OutputStreamWriter(outputStream, "UTF-8");
这样可以确保以指定的字符编码写入字节流。