请教错误捕捉的问题

xxdxbasen 2007-08-16 07:29:27
public static void CopyFile(File in, File out) {
FileInputStream fis = null;
FileOutputStream fos = null;
try {
fis = new FileInputStream(in);
fos = new FileOutputStream(out);
byte[] buf = new byte[1024];
int i = 0;
while ((i = fis.read(buf)) != -1) {
fos.write(buf, 0, i);
}
//这是第一部分:
fis.close();
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {//finally这儿是第二部分
if(fis != null){
try {
fis.close();
fis = null;
} catch (IOException e) {
e.printStackTrace();
}
}
if(fos != null){
try {
fos.close();
fos = null;
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

问题1:我用第一部分的写法,Jtest时候会出错,说没有关闭,这样写不严谨对吗?
问题2:用第二部分的写法,那么我假设try部分不出错,而在finally部分关闭fis出错,那么执行e.printStackTrace();下面fos的关闭就不会执行了对吧,那么fos就无法关闭了对吗?
问题3:用第二部分的写法,我假设while循环里面运行到一半出错,那么首先抛出上面的IO错误,然后执行finally,而关闭文件时候又出错,那么会覆盖之前的信息而只看到后面的吗?
其实我的问题概括起来就是这个问题怎么写最合理,出错时候的运行机理是怎样的?请大家指点一下


...全文
173 回复 打赏 收藏 转发到动态 举报
写回复
用AI写文章
回复
切换为时间正序
请发表友善的回复…
发表回复

62,623

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧