JAVA在JDK1.7起可以自动关闭IO流,不管再去写繁琐的try catch finally 了
比如一个简单的例子 以前是这样写的
public String getTextByFilePath(String pathname){
File file = new File(pathname);
FileInputStream fileInputStream = null;
try{
fileInputStream = new FileInputStream(file);
byte[] bytes = new byte[(int) file.length()];
//读取
fileInputStream.read(bytes);
return new String(bytes, "UTF-8");
} catch (IOException e) {
e.printStackTrace();
return "";
}finally {
if(fileInputStream!=null){}
try {
//关闭流
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
非常繁琐,且代码太长不美观
1.7之后可以用这种方式
public String getTextByFilePath(String pathname){
File file = new File(pathname);
try (FileInputStream fileInputStream = new FileInputStream(file);){
byte[] bytes = new byte[(int) file.length()];
//读取
fileInputStream.read(bytes);
return new String(bytes, "UTF-8");
} catch (IOException e) {
e.printStackTrace();
return "";
}
}
简单 so easy