/**
* 为了保证流资源一定可以执行关闭操作,需要使用try-catch-finally
*/
public void testFileReader(){
FileReader fileReader = null;
try {
// 1. 实例化File类对象,指明要操作的对象
File file = new File("hello.txt");
// 2. 提供具体的流
fileReader = new FileReader(file);
// 3. 数据的读入过程
// read() 返回读入的一个字符。如果达到文件末尾,返回-1
int data;
while(-1 != (data = fileReader.read())){
System.out.print((char)data);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
// 4. 流的关闭
if(fileReader != null) fileReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 使用read()的重载方法
*/
public void testFileReader1(){
FileReader fileReader = null;
try {
// 1. file 实例化
File file = new File("hello.txt");
// 2. FileReader流的实例化
fileReader = new FileReader(file);
// 3. 读入的操作
// read(char[] cbuf) 返回每次读入cbuf数组中的字符个数。如果达到文件末尾返回-1
char[] cbuf = new char[2];
int len;
while ((len = fileReader.read(cbuf)) != -1){
// 方式一
/*for (int i = 0; i < len; i++) {
System.out.print(cbuf[i]);
}*/
// 方式二
String str = new String(cbuf,0,len);
System.out.print(str);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
// 4. 关闭资源
if(fileReader != null)fileReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
版权声明:本文为mnmnwq原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。