字符流
当使用字节流读取文本文件时,可能会有一个小问题。就是遇到中文字符时,可能不会显示完整的字符,那是因为一个中文字符可能占用多个字节存储。所以Java提供一些字符流类,以字符为单位读写数据,专门用于处理文本文件。
FileReader和FileWriter类
FileReader 和 FileWriter 字符流对应了 FileInputStream和 FIleOutputStream类. 方法比较类似, 接下来我们就简单的使用字符流.
【FileReader】读取字符数据
- 读取字符: read() 方法,每次可以读取一个字符的数据,提升为int类型,读取到文件末尾,返回 -1 ,循环读取,代码使用演示:
public class Test1 {
public static void main(String[] args) {
try(FileReader fr = new FileReader("day16\\testFiles\\readTest");) {
int len;
while ((len = fr.read()) != -1) {
System.out.println((char)len);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
输出结果:
注意: 虽然读取了一个字符,但是会自动提升为int类型.
- 使用字符数组读取: read(char[] chars) ,每次读取多个字符到数组中,返回读取到的有效字符个数,读取到末尾时,返回 -1 ,代码使用演示:
public class Test1 {
public static void main(String[] args) {
try(FileReader fr = new FileReader("day16\\testFiles\\readTest");) {
int len;
char[] chars = new char[2];
while ((len = fr.read(chars)) != -1) {
System.out.println(new String(chars));
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
运行结果:
最后一行获取到了无效字符, 优化代码演示:
public class Test1 {
public static void main(String[] args) {
try(FileReader fr = new FileReader("day16\\testFiles\\readTest");) {
int len;
char[] chars = new char[2];
while ((len = fr.read(chars)) != -1) {
System.out.println(new String(chars,0,len));
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
运行结果:
【FileWriter】基本写出数据
FileWriter类的使用跟FileOutputStream的使用及其类似, 这里就不再啰嗦了, 各位看官可以选择点击下方链接复习下.
Java中字节流