编码转换流

字节流:针对二进制文件
字符流:针对文本文件,读写容易出现乱码的现象,在读写时,最好指定编码集为UTF-8

概述

编码转换流(InputStreamReader/OutputStreamWriter)主要进行编码的转换,用来解决字符流读写乱码的问题

使用的工具API

OutputStreamWriter :
OutputStreamWriter(OutputStream out)把传入的字节流转成字符流
OutputStreamWriter(OutputStream out ,String charsetName)把Unicode转成其他编码输出

InputStreamReader :
InputStreamReader(InputStream in) 把传入的字节流转成字符流
InputStreamReader(InputStream in,String charsetName)读取其他编码转成Unicode

常见字符编码表

image.png

示例代码

  1. package cd.tedu.encoding;
  2. import java.io.*;
  3. import java.nio.charset.StandardCharsets;
  4. /**
  5. * 编码转换测试
  6. */
  7. public class TestEncode {
  8. public static void main(String[] args) {
  9. //f1();
  10. f2();
  11. }
  12. private static void f1() {
  13. OutputStreamWriter out = null;
  14. try {
  15. //out = new OutputStreamWriter(new FileOutputStream("1.txt"),"gbk");
  16. //out = new OutputStreamWriter(new FileOutputStream("1.txt"), StandardCharsets.ISO_8859_1);
  17. out = new OutputStreamWriter(new FileOutputStream("1.txt"), StandardCharsets.UTF_8);
  18. out.write("一拳超人&鬼灭之刃");
  19. System.out.println("成功");
  20. } catch (Exception e) {
  21. System.out.println("失败");
  22. e.printStackTrace();
  23. } finally {
  24. try {
  25. out.close();
  26. } catch (IOException e) {
  27. e.printStackTrace();
  28. } finally {
  29. try {
  30. out.close();
  31. } catch (IOException e) {
  32. e.printStackTrace();
  33. }
  34. }
  35. }
  36. }
  37. private static void f2() {
  38. InputStreamReader in = null;
  39. try {
  40. //in = new InputStreamReader(new FileInputStream("1.txt"));
  41. //in = new InputStreamReader(new FileInputStream("1.txt"),"gbk");
  42. //in = new InputStreamReader(new FileInputStream("1.txt"), StandardCharsets.ISO_8859_1);
  43. in = new InputStreamReader(new FileInputStream("1.txt"), StandardCharsets.UTF_8);
  44. //System.out.println(in.read());
  45. char[] ch = new char[8192];
  46. int len = in.read(ch);
  47. System.out.println(new String(ch,0,len));
  48. } catch (Exception e) {
  49. e.printStackTrace();
  50. } finally {
  51. try {
  52. in.close();
  53. } catch (IOException e) {
  54. e.printStackTrace();
  55. }
  56. }
  57. }
  58. }