今天写一个FileReader这个流的使用,这个流是一个输入流,但是跟前面的FileInputStream不同,这个只能读取普通文本文件,不能读取word等文件,因为这个是一个字符流。但是使用的方法跟FileInputStream大同小异,可以说前面的16流,只要把FileInputStream和FileOutputStream学习了,其他的流都是大同小异。所以,我认为16个流,只用学习好两个流,其他的14个流不攻自破。
需求:利用FileReader读取resource/data/test.txt的文件内容,并在控制台上显示
,具体代码如下:
public static void main(String[] args) {
String path = FileReaderTest.class.getResource("/data/test.txt").getPath();
FileReader fileReader = null;
try {
fileReader = new FileReader(path);
int count = 0;
char[] a = new char[6];
while ((count = fileReader.read(a))!= -1) {
System.out.println(new String(a,0,count));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (fileReader != null) {
try {
fileReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
上面的代码和FileInputStream的代码不同的就是这个read使用的是char[]数组来做缓冲,而后者是使用byte[]数组来做缓冲,其他都是一样的,所以说两者的用法都是一样的,前者是字符流,使用char[],后者是字节流,使用byte[]。
代码的运行截图: