| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556 |
- package course;
- import java.io.*;
- /**
- * @author WanJl
- * @version 1.0
- * @title Demo01
- * @description 转换流
- * @create 2026/8/8
- */
- public class Demo01 {
- /*
- 我们讲字符流的时候,说过字符集的概念,
- 不同的字符集虽然都能转换成字节(二进制数)但是,同一个字节,在不同的字符集中表示的含义是不一样的。
- 字符--编码-->字节--解码-->字符
- 如果使用字符集A进行编码,使用字符集B进行解码,就会出现字符集乱码。
- 但是如果出现这样情况:
- 我们对于一个文件需要追加写入一些内容。但是这个文件本身是使用GBK编码的。
- 而我们只能使用UTF-8字符集。那么怎么处理?
- 我们可以使用转换流,对A字符集的文件,进行转换,转为B字符集的文件。
- InputStreamReader:是字节流到字符流的桥梁,父类是Reader
- 他是读取字节,并且使用指定的字符集把它解码为字符。
- 它使用的字符集可以有名称指定,也可以直接使用平台默认字符集。
- OutputStreamWriter:是字符流到字节流的桥梁,父类是Writer
- 它是读取字符,使用指定的字符集把它编码为字节。
- 构造方法:
- public InputStreamReader(InputStream in) 使用默认字符集创建InputStreamReader对象
- public InputStreamReader(InputStream in, String charsetName) 使用charsetName指定的字符集创建InputStreamReader对象
- public OutputStreamWriter(OutputStream out) 使用默认字符集创建OutputStreamWriter对象
- public OutputStreamWriter(OutputStream out, String charsetName) 使用charsetName指定的字符集创建OutputStreamWriter对象
- 案例:
- 使用UTF-8字符集打开abc.txt文件,并且转换成GBK字符集的hello.txt文件
- */
- public static void main(String[] args) throws IOException {
- //使用UTF-8字符集打开abc.txt文件
- InputStreamReader isr = new InputStreamReader(new FileInputStream("D:\\abc.txt"),"UTF-8");
- //把内容使用GBK字符集写入到hello.txt文件
- OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("D:\\hello.txt"),"GBK");
- char[] chars=new char[1024];
- int count;
- while ((count=isr.read(chars))!=-1){
- osw.write(chars,0,count);
- }
- osw.close();
- isr.close();
- }
- }
|