2010-12-06 75 views
0

我的下载文件的方法。这有点简化,我删除了第三个参数 - DownloadListener,我使用它来通知调用者关于下载进度。如何下载文件并正确处理异常?

public static boolean downloadFile(String url, File file) { 
    try { 
     HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection(); 
     connection.connect(); 

     FileOutputStream fos = new FileOutputStream(file); 
     InputStream is = connection.getInputStream(); 

     byte[] buffer = new byte[1024]; 
     int len = 0; 
     while ((len = is.read(buffer)) > 0) { 
      fos.write(buffer, 0, len); 
     } 

     is.close(); 
     fos.flush(); 
     fos.close(); 
     return true; 
    } catch (IOException e) { 
     if (file.exists()) 
      file.delete(); 
     return false; 
    } 
} 

我猜测,异常没有被正确处理,但如果我把close()方法调用进入finally块,他们将不得不通过try-catch块这会显得很凌乱包围。必须有一些更清晰的方式来正确地下载Java文件。另一件事是,我应该拨打connection.disconnect()

回答

4

直到Java 7的ARM。您是对的,那么您通常需要在finally区块中嵌套try-finally区块,以清楚地清理多个资源。如果在线完成,正确的做法看起来不太整齐。

这通常是提取静态辅助方法(如类似IOUtils.closeConnection())的一个很好的候选方案;该方法可以捕获任何异常,以避免异常停止进一步的资源关闭。

1
 FileOutputStream fos = null; 
    InputStream is = null; 
    try { 
      HttpURLConnection connection = 
        (HttpURLConnection) new URL(url).openConnection(); 
      connection.connect(); 

      fos = new FileOutputStream(file); 

      is = = connection.getInputStream(); 

      byte[] buffer = new byte[1024]; 
      int len = 0; 
      while ((len = is.read(buffer)) > 0) { 
       fos.write(buffer, 0, len); 
      } 


      return true; 
     } catch (IOException e) { 
      if (file.exists()) 
       file.delete(); 
      return false; 
     }finally{ 
      myClose(is); 
      myFlush(fos); 
      myClose(fos); 

    }  } 

    public void myClose(Closable c){ 
     if(c == null) 
     return; 
     try{ 
     c.close(); 
     }catch(IOException ex) 
     //perform necessary things 
     } 
    } 
    public void myFlush(Flushable f){ 
     if(f == null) 
     return; 
     try{ 
     f.flush(); 
     }catch(IOException ex) 
     //perform necessary things 
    } 
+1

什么是`Colsable`? – 2010-12-06 10:28:16

2

我的建议是,所使用的每个资源必须在finally区块中关闭(释放)。当您打开未关闭的连接并尝试建立另一个连接并且以前的资源尚未释放时,您不需要这种情况。

0

将'is'或'fos'放在catch中以使其无法访问。

+0

请详细说明。 – 2010-12-06 10:59:43