1.第一种写法。BufferedOutputStream bos = null;
try {
bos = new BufferedOutputStream(new FileOutputStream("d:/123.txt"));
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} finally {
try {
bos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}2.第二种写法。BufferedOutputStream bos = null;
try {
bos = new BufferedOutputStream(new FileOutputStream("d:/123.txt"));
bos.close();
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} 3.第三种写法。BufferedOutputStream bos = null;
try {
bos = new BufferedOutputStream(new FileOutputStream("d:/123.txt"));
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
bos.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}请问哪种更好一些,为什么?
try {
bos = new BufferedOutputStream(new FileOutputStream("d:/123.txt"));
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} finally {
try {
bos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}2.第二种写法。BufferedOutputStream bos = null;
try {
bos = new BufferedOutputStream(new FileOutputStream("d:/123.txt"));
bos.close();
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} 3.第三种写法。BufferedOutputStream bos = null;
try {
bos = new BufferedOutputStream(new FileOutputStream("d:/123.txt"));
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
bos.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}请问哪种更好一些,为什么?
第二种情况出现异常,就无法关闭了。
第三种情况如果不是FileNotFoundException,那么之后的close语句也不会执行。
这样就需要在finally里释放资源因为只有这样才能保证释放资源行在任何情况下都被执行
- 第一种最好
- bos.close(); 前面加 if(bos != null)
- Java 7 以后可以 try on resource, 所以在 finally 里面 写
try{ if(xxx!=null) xxx.close(); } catch(...) {}
这种难看又啰嗦的问题没有了