jdk1.7版本起,可以自动关闭IO流
如:获取一个文件内容,以前通常是这样写:
/**
* 获取文件内容
* @param file 文件
* @return 内容
*/
public String getText(File file){
FileInputStream fis = null;
try {
fis = new FileInputStream(file);
byte[] b = new byte[(int) file.length()];
fis.read(b);
return new String(b, \"UTF-8\");
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return \"\";
}
但jdk1.7及以后就可以改写为下面格式了:把需要关闭的资源声明再try的小括号里
/**
* 获取文件内容
* @param file 文件
* @return 内容
*/
public String getText(File file){
try(FileInputStream fis = new FileInputStream(file)) {
byte[] b = new byte[(int) file.length()];
fis.read(b);
return new String(b, \"UTF-8\");
} catch (IOException e) {
e.printStackTrace();
}
return \"\";
}
这样代码就节省了许多,看着也美观。
继续阅读与本文标签相同的文章
-
flex布局和grid布局
2026-05-18栏目: 教程
-
语音顶会Interspeech 论文解读|Constrained output embeddings for end-to-end code-switching speech recognition with only monolingual data
2026-05-18栏目: 教程
-
《Android应用开发进阶》| 每日读本书
2026-05-18栏目: 教程
-
“阿里云十年,因为有我而不同”,征文活动开始了!
2026-05-18栏目: 教程
-
玩转 Drone CI
2026-05-18栏目: 教程
