2013-12-09 33 views
0

我使用下面的代碼來下載android.code中的zip文件,工作正常,但有時下載失敗並拋出套接字異常。特別是當互聯網連接速度慢(我猜)。我也發佈了logcat錯誤消息的屏幕截圖。從android下載文件時出現套接字異常

int count;

 URL url = new URL(URL); 
     URLConnection conexion = url.openConnection(); 
     conexion.connect(); 

     int lenghtOfFile = conexion.getContentLength(); 
     //Log.e("ANDRO_ASYNC", "Lenght of file: " + "="+lenghtOfFile); 

     InputStream input = new BufferedInputStream(url.openStream()); 
     OutputStream output = new FileOutputStream(StorezipFileLocation); 

     byte data[] = new byte[lenghtOfFile]; 

     long total = 0; 

     while ((count = input.read(data)) != -1) { 
      total += c![enter image description here][1]ount; 
      publishProgress(""+(int)((total*100)/lenghtOfFile)); 
      output.write(data, 0, count); 
     } 

     output.flush(); 
     output.close(); 
     input.close(); 

enter image description here

回答

0

日誌不說,凡在你的代碼發生崩潰。沒有更多的信息沒有出現在你的截圖中?

它似乎失敗了您的文件輸入流的關閉方法。 你可以簡單地環繞close的調用()與try catch塊和你流設置爲null(如果它失敗的收盤)

+0

我只從logcat得到這個錯誤 – Ruban

+0

如果執行「close()」行時發生錯誤,那麼你的下載應該完成。你有沒有嘗試過抓住免疫?否則,你知道錯誤發生在哪裏嗎?在等待數據時? –

1

connection reset by peer通常意味着你所談論到對等至極認爲連接已經已關閉。我不明白爲什麼它會在關閉FileOutputStream時發生。

此外,異常不會發生在您的代碼中,但在終結器中。有可能當出現問題時,您在上層捕獲異常並保持連接和文件打開?放棄的連接被finalyser關閉,但已經太晚了。

我不確定它是否可以解決問題,但使用finally子句確保文件和連接已正確關閉是一個好習慣。