Java——IO类 字符流概述

时间:2022-04-10 22:53:47

body, table{font-family: 微软雅黑}
table{border-collapse: collapse; border: solid gray; border-width: 2px 0 2px 0;}
th{border: 1px solid gray; padding: 4px; background-color: #DDD;}
td{border: 1px solid gray; padding: 4px;}
tr:nth-child(2n){background-color: #f8f8f8;}

字符流出现的原因及思想

    ☞由于字节流操作中文不是特别方便,所以,java就提供了字符流。
    ☞字符流=字节流+编码表。

编码表概述和常见的编码表
█ 编码表
      ☞由字符及其对应的数值组成的一张表

█ 常见编码表

      ☞ASCII/Unicode 字符集
      ☞ISO-8859-1   Latin-1
      ☞GB2312/GBK/GB18030
      ☞BIG5
      ☞UTF-8

public class TestMain {
/*
* getBytes(String charsetName);
          使用指定的字符集将此 String 编码为 byte 序列,并将结果存储到一个新的 byte 数组中。
   String(byte[] bytes, String charsetName);
          通过使用指定的 charset 解码指定的 byte 数组,构造一个新的 String。
*/
        public static void main(String[] args) {
                String string = "hello world" ;       
                byte[] bytes = string.getBytes();   //编码
                for(int i=0;i<bytes.length;i++){
                        System.out.print(bytes[i]);   //输出字节码
                }
                //解码
                String jiemaStrin = new String(bytes);  //通过使用平台的默认字符集解码指定的 byte 数组,构造一个新的 String。//这个平台是操作系统,默认的编码GBK
                System.out.print('\n'+jiemaStrin);
        }
}
Java——IO类 字符流概述
public static void main(String[] args) throws UnsupportedEncodingException {
                String string = "hello world 梅浩" ;
                //编码
                byte[] bytes = string.getBytes("utf-8");  //参数不写就是用系统默认GBK,但是我这被改成 utf-8 了;
                for(int i=0;i<bytes.length;i++){
                        System.out.print(bytes[i]);    //输出字节码
                }
                //解码
                //String jiemaStrin = new String(bytes);  //通过使用平台的默认字符集解码指定的 byte 数组,构造一个新的 String。(我这里已经把默认的改成utf-8了)
                String jiemaStrin = new String(bytes,"utf-8");                //这个平台是操作系统,默认的编码GBK
                System.out.print('\n'+jiemaStrin);
        }
}
Java——IO类 字符流概述

//unicode码 :java 虚拟机内部使用
String str = "梅浩";      //存字符串常量区就是用 unicode 码存的。

字符流概述(转换流)
█ OutputStreamWriter 字符输出流

     ☞public OutputStreamWriter(OutputStream out);           //创建使用默认字符编码的 OutputStreamWriter。
     ☞public OutputStreamWriter(OutputStream out,String charsetName);   

█ InputStreamReader 字符输入流

     ☞public InputStreamReader(InputStream in);              //创建一个使用默认字符集的 InputStreamReader。
     ☞public InputStreamReader(InputStream in,String charsetName);       // 创建使用指定字符集的
Java——IO类 字符流概述