zl程序教程

您现在的位置是:首页 >  .Net

当前栏目

IO流-字符流

2023-04-18 15:45:48 时间

IO流-字符流

为什么会出现字符流

编码表






编码:
    byte[] getBytes():使用平台的默认字符集将该 String编码为一系列字节,将结果存储到新的字节数组中
    byte[] getBytes(String charsetName):使用指定的字符集将该 String编码为一系列字节,将结果存储到新的字节数组中
解码:
    String(byte[] bytes):通过使用平台的默认字符集解码指定的字节数组来构造新的 String
    String(byte[] bytes, String charsetName):通过指定的字符集解码指定的字节数组来构造新的 String
 编码和解码要统一为一个字符集,否则就会出现乱码现象. 编解码要么都用"GBK" ,要么都用"UTF-8"(建议)
 */
package IO.StringStream;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;

public class String_Coding_Decoding {
    public static void main(String[] args) throws UnsupportedEncodingException {
        //定义一个字符串
        String s = "中国";
        //编码  和默认的方法一样  用Arrays类的toString 方法输出在控制台
        byte[] bytes = s.getBytes(StandardCharsets.UTF_8);
        System.out.println(Arrays.toString(bytes));//[-28, -72, -83, -27, -101, -67]  三个字节构成一个汉字
        byte[] bytes1 = s.getBytes("GBK");
        System.out.println(Arrays.toString(bytes1));//[-42, -48, -71, -6]   两个字节构成一个汉字
        //解码    编码和解码要统一为一个字符集,否则就会出现乱码现象.
        System.out.println(new String(bytes));  //中国
        System.out.println(new String(bytes,"GBK"));  //涓浗(乱码)
    }
}

1. OutputStreamWriter(OutputStream out)
    创建一个使用默认字符编码的OutputStreamWriter。
2. OutputStreamWriter(OutputStream out, Charset cs)
    创建一个使用给定字符集的OutputStreamWriter。

3.  InputStreamReader(InputStream in)
    创建一个使用默认字符集的InputStreamReader。
4.  InputStreamReader(InputStream in, Charset cs)
    创建一个使用给定字符集的InputStreamReader。
 */
package IO.StringStream;

import java.io.*;

public class Reader_Writer_1 {
    public static void main(String[] args) throws IOException {
        //OutputStreamWriter(OutputStream out): 创建一个使用默认字符编码的OutputStreamWriter。
//        OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("java.txt"));//默认字符集UTF-8
        //指定为GBK字符集, 打开文件时,和用默认字符集UTF-8读取时就会出现乱码现象.
        OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("java.txt"),"GBK");
        osw.write("中国");
        osw.close();
        // InputStreamReader(InputStream in): 创建一个使用默认字符集的InputStreamReader。
//        InputStreamReader isr = new InputStreamReader(new FileInputStream("java.txt"));
        //上面写入改为GBK后,读取也要和上面一样, 就能读出中文了.
        InputStreamReader isr = new InputStreamReader(new FileInputStream("java.txt"),"GBK");
        //字符流读取中文字符也有两种方式, 分别是 一次读取一个字节, 一次读取一个字节数组
        int i;
        while((i=isr.read())!=-1){
            System.out.print((char) i);
        }       //读和写的字符集要相同,否则会出现乱码现象.
        isr.close();
    }
}