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");
這樣可以確保以指定的字符編碼寫入字節流。