0

我正在使用以下代码来确保文件内容成功写入磁盘

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(),我拔下电缆,它尝试了两次,然后第三次插入电缆。函数成功返回。正如我在while循环中一样。现在,当我来排队时

Asset asset = cm.getAsset();

我明白了Connection Reset by peer exception。它会跳过此资产,然后再次正常启动。为什么 ?为什么我得到connection Reset by peer exception?如果我因为拔掉电缆而得到这个异常,那么我也应该为所有其他资产得到它,但我只在下一次迭代中得到这个异常,然后它开始正常工作,我的意思是,Asset asset = cm.getAsset();在第一次抛出后,行不会抛出异常时间?

为什么会这样?我怎样才能克服它?

我正在使用 SQL Server 2008 作为数据库。

谢谢

4

1 回答 1

0

您可以尝试在 close() 方法之前使用 flush() 方法

于 2013-05-15T11:45:28.873 回答