【Java】指定编码表的两种方式——String类的构造方法和转换流

  1. 使用文件字符输入流+String类构造函数指定编码表
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Arrays;

public class Demo05 {
    public static void main(String[] args) throws IOException {
        FileInputStream fis = new FileInputStream("D:\\Workspaces\\IdeaProjects\\basic-code\\a.txt");
        byte[] bytes = new byte[6];
        fis.read(bytes);//int read(byte[] b)    从输入流读取一定数量(b)的字节,并将其存储在缓冲区数组bytes中;返回值是读取到的有效字节个数
        System.out.println(Arrays.toString(bytes));//打印的是编码表
        System.out.println(new String(bytes));//将字节数组转换成字符串打印,使用的是String类的方法:
        //    String(byte[] bytes, int offset, int length) offset:数组的开始索引;length:转换的字节长度
        System.out.println(new String(bytes, "GBK"));//String类的构造方法还可以指定字符集解码,如指定GBK字符集
		fis.close();
    }
}

  中文操作系统下创建的txt文件的编码默认是ANSI,即GBK,所以这里使用String(bytes, “GBK”)。

  1. 使用转换输入流指定编码表
import java.io.*;

public class Demo04ArrayListReturn {
    public static void main(String[] args) throws IOException {
        read_gbk();
    }
    private static void read_gbk() throws IOException {
        InputStreamReader isr = new InputStreamReader(new FileInputStream("D:\\Workspaces\\IdeaProjects\\gbk.txt"), "gbk");
        int len = 0;
        while ((len = isr.read())!=-1) {
            System.out.println((char) len);
        }
        isr.close();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值