我使用以下代码确保将文件内容成功写入磁盘
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();
if (source == null) {
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);
//add for successfull
} else {
log.debug("skipping creation of asset");
}
} catch (Exception e) {
if(count < 3){
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);
}
} else {
log.debug(e.getClass().getName());
e.printStackTrace();
}
} finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
}
我正在调用此代码
while(iter.hasNext()) {
CourseMaterials cm = iter.next();
String url;
try {
Asset asset = cm.getAsset();
List<AssetVersion> av = asset.getAssetVersions();
} catch (Exception e1) {
log.debug("Bad asset so skipping...");
e1.printStackTrace();
continue;
}
....
try {
URL earl = new URL(visualElementURL);
scormFileWriter.copyFileFromUrl(earl, new File(absoluteFileName), 0);
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
现在我的尝试是这样的,当我来功能copyFileFromUrl()
时,我拔掉电缆,它会尝试两次,然后第三次插上电缆。该函数成功返回。因为我在循环中。在那之后我来排队
Asset asset = cm.getAsset();
我得到Connection Reset by peer exception
。它会跳过此资产,然后再次正常启动。为什么?为什么我得到connection Reset by peer exception
?如果我因为拔掉电缆而得到这个例外,那么我也应该为所有其他资产得到它,但我只是为下一次迭代得到这个例外,然后它开始工作正常,我的意思是然后行Asset asset = cm.getAsset();
抛出投掷第一次后也不例外?
为什么会这样?我怎么能克服它?
我正在使用SQL Server 2008作为数据库。
由于
答案 0 :(得分:0)
您可以尝试在close()方法
之前使用flush()方法