我很想确保 url 中的内容成功写入文件。为此,我使用以下代码
public void copyFileFromUrl(URL source, File target, int count) throws IOException {
InputStream in = null;
OutputStream out = null;
if (target != null) {
try {
if (!target.exists()) {
target.createNewFile();
log.debug("target file created for " + target);
log.debug("downloading source .... " + source);
if (source == null) {
log.debug("Null source .... " + ScormFileWriter.class.getName());
return;
} else {
in = source.openStream();
}
out = new FileOutputStream(target);
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
log.debug("The contents from the URL: " + source + " are successfully written to the file " + target);
} else {
log.debug("skipping creation of asset");
}
} catch (Exception e) {
if(count < 3){
log.debug("trouble with " + target);
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
// Attempt to delete it
boolean success = target.delete();
if (!success) {
log.debug("Unable to delete " + target);
} else {
copyFileFromUrl(source, target, ++count);
}
}
log.debug("trouble in downloading source after trying " + count + " times: " + source);
e.printStackTrace();
} finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
}
现在假设在第一次调用函数时发生了什么
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
我拔掉电缆,抛出异常,代码来捕获块并再次调用该函数。现在我插入电缆,这次while
循环完成并且线路
log.debug("The contents from the URL: " + source + " are successfully written to the file " + target);
打印,代码来到 finally 块,然后代码来到这两行
log.debug("trouble in downloading source after trying " + count + " times: " + source);
e.printStackTrace();
为什么?这次没有抛出异常,一切正常,为什么代码来了 catch 块?这个时候finally之后代码应该恢复正常了吧?
谢谢