一、字节流读取字符的问题
通过以下程序读取带有中文件的文件。
public class CharStreamDemo {
public static void main(String[] args) throws IOException {
//给文件中写中文
writeCNText();
//读取文件中的中文
readCNText();
}
//读取中文
public static void readCNText() throws IOException {
FileInputStream fis = new FileInputStream("c:\\cn.txt");
int ch = 0;
while((ch = fis.read())!=-1){
System.out.println(ch);
}
}
//写中文
public static void writeCNText() throws IOException {
FileOutputStream fos = new FileOutputStream("c:\\cn.txt");
fos.write("a北京欢迎你".getBytes());
fos.close();
}
}
上面程序在读取含有中文的文件时,我们并没有看到具体的中文,而是看到一些数字,这是什么原因呢?既然看不到中文,那么我们如何对其中的中文做处理呢?要解决这个问题,我们必须研究下字符的编码过程。
二、字符输入流Reader
上述程序中我们读取拥有中文的文件时,使用的字节流在读取,那么我们读取到的都是一个一个字节。只要把这些字节去查阅对应的编码表,就能够得到与之对应的字符。API中给我们已经提供了读取相应字符的功能流对象,Reader,读取字符流的抽象超类。
- read():读取单个字符并返回
- read(char[]):将数据读取到数组中,并返回读取的个数。
三、FileReader类
查阅FileInputStream的API,发现FileInputStream 用于读取诸如图像数据之类的原始字节流。要读取字符流,请考虑使用 FileReader。
打开FileReader的API介绍。用来读取字符文件的便捷类。此类的构造方法假定默认字符编码和默认字节缓冲区大小都是适当的
构造方法
四、FileReader读取包含中文的文件
使用FileReader读取包含中文的文件
public class CharStreamDemo {
public static void main(String[] args) throws IOException {
//给文件中写中文
writeCNText();
//读取文件中的中文
readCNText();
}
//读取中文
public static void readCNText() throws IOException {
FileReader fr = new FileReader("D:\\test\\cn.txt");
int ch = 0;
while((ch = fr.read())!=-1){
//输出的字符对应的编码值
System.out.println(ch);
//输出字符本身
System.out.println((char)ch);
}
}
//写中文
public static void writeCNText() throws IOException {
FileOutputStream fos = new FileOutputStream("D:\\test\\cn.txt");
fos.write("a北京欢迎你".getBytes());
fos.close();
}
}