//JDK1.7之前,资源需要手动关闭
public void readFile() throws FileNotFoundException {
FileReader fr = null;
BufferedReader br = null;
try{
fr = new FileReader("d:/input.txt");
br = new BufferedReader(fr);
String s = "";
while((s = br.readLine()) != null){
System.out.println(s);
}
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
br.close();
fr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
//JDK1.7之后 try with resource
//资源终止被自动关闭
public void readFileNew() throws FileNotFoundException {
try(
FileReader fr = new FileReader("d:/input.txt");
BufferedReader br = new BufferedReader(fr)
){
String s = "";
while((s = br.readLine()) != null){
System.out.println(s);
}
} catch (IOException e) {
e.printStackTrace();
}
}
【简单整理】try with resource简单代码实现
最新推荐文章于 2024-06-30 11:56:31 发布