FileReader(文件字符输入流)
应用案例:使用 FileReader 从 story.txt 读取内容,并显示
第一种方式:使用 read()
public class FileReader01 {
public static void main(String[] args) {
}
@Test
public void readFile01(){
String filePath = "D:\\story.txt";
FileReader fileReader =null;
int data = 0;
try {
fileReader = new FileReader(filePath);
while ((data = fileReader.read()) != -1){
System.out.print((char)data);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fileReader != null){
try {
fileReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
第二种方式:使用 read(char[])
public class FileReader01 {
public static void main(String[] args) {
}
@Test
public void readFile02(){
String filePath = "D:\\story.txt";
FileReader fileReader =null;
int readLen = 0;
char[] buf = new char[8];
try {
fileReader = new FileReader(filePath);
while ((readLen = fileReader.read(buf)) != -1){
System.out.print(new String(buf,0,readLen));
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fileReader != null){
try {
fileReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}