Demo01.java 2.6 KB

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