s-day10-转换流_按照指定编码写数据(OutputStreamWriter)

This commit is contained in:
2026-08-12 10:49:43 +08:00
parent 8f0e4d8617
commit 473def2b44
@@ -0,0 +1,43 @@
package com.inmind.transfer_stream02;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
/*
转换流_按照指定编码写数据(OutputStreamWriter)
OutputStreamWriter是从字符流到字节流的桥梁: 编码
构造方法:
OutputStreamWriter(OutputStream out) 创建一个使用默认字符编码的OutputStreamWriter。
OutputStreamWriter(OutputStream out, String charsetName) 创建一个使用命名字符集的OutputStreamWriter。
常用方法:
close
flush
void write(char[] cbuf) 写入一个字符数组。
abstract void write(char[] cbuf, int off, int len) 写入字符数组的一部分。
void write(int c) 写一个字符
void write(String str) 写一个字符串
void write(String str, int off, int len) 写一个字符串的一部分。
*/
public class Demo08 {
//使用转换输出流,指定utf-8编码方式输出内容到文件中
public static void main(String[] args) throws Exception{
FileOutputStream fos = new FileOutputStream("D:\\io_test\\file_utf81.txt");
// OutputStreamWriter osw = new OutputStreamWriter(fos);
OutputStreamWriter osw = new OutputStreamWriter(fos,"utf-8");
osw.write("呵呵,今天不下雨了,abc123");
osw.flush();
osw.close();
}
//使用转换输出流,指定GBK编码方式输出内容到文件中
public static void method() throws Exception {
FileOutputStream fos = new FileOutputStream("D:\\io_test\\file_gbk1.txt");
OutputStreamWriter osw = new OutputStreamWriter(fos,"GBK");
osw.write("呵呵,今天不下雨了,abc123");
osw.flush();
osw.close();
}
}