当前位置: 代码迷 >> J2EE >> FileOutputStream的关闭有关问题
  详细解决方案

FileOutputStream的关闭有关问题

热度:28   发布时间:2016-04-17 23:00:40.0
FileOutputStream的关闭问题
try
{
out = new FileOutputStream(file_name);
out.write("\xxx".getBytes());
out.close();
}
catch(FileNotFoundException e)
{
}
catch(IOException e)
{
}


以上这段,如果发生异常的话,可能会执行不到close()方法,但是把close写在异常里,又要重新写一遍try和catch,很麻烦看上去也很奇怪。有没有什么好点的解决方法?

------解决思路----------------------

        FileOutputStream out = null;
try
{
    out = new FileOutputStream(file_name);
    out.write("\xxx".getBytes());
}
catch(FileNotFoundException e){

}
catch(IOException e){

}finally{
if(out != null){
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}           
}
}