在使用FileReader类读取文件时,必须先调用FileReader()构造方法创建FileReader类的对象,再利用它来调用read()方法
- FileReader类的构造方法:public FileReader(String name)—根据文件名称创建一个可读取的输入流对象
- 注意:Java把每个汉字和英文字母均作为一个字符对待,但把Enter键生成的回车换行符“\r\n”作为两个字符
4. 实例代码
read()方法
/*
使用FileReader的read方法读取文件内容
*/
import ;
import ;
public class $1_FileRead {
public static void main(String[] args) throws IOException {
//使用FileReader类读取文件,使用read()依次读取字符,如果到达文件末返回-1
FileReader fr = new FileReader("");
int data;
while((data=())!=-1){
((char)data);
}
(); //垃圾回收不会处理,需要手动关闭;为保证关闭,可在if判断后用try... catch语句包围
}
}
read(char[] cbuf, int start, int len)方法
/*
使用FileReader类的read(cbuf)缓冲读取文件内容
*/
import ;
import ;
import ;
public class $2_FileRead {
public static void main(String[] args) throws IOException {
File file=new File("");
FileReader fr=new FileReader(file);
char[] cbuf=new char[5];
int len;
while((len=(cbuf))!=-1){
for (int i = 0; i < len; i++) { //缓冲读取,注意此处使用len而不能使用,否则会有多余的输出
(cbuf[i]);
}
}
/*方法二:
while((len=(cbuf))!=-1){
String str=new String(cbuf,0,len);
(str);
}
}
*/
();
}
}