- 使用文件字符输入流+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”)。
- 使用转换输入流指定编码表
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();
}
}