2011-11-21 104 views
1

可能重複:
Android:「Unexpected end of stream」 exception downloading large files下載文件時流結束錯誤?

我下載與下面的下面的代碼文件。該文件是大約。大小5MB。然而,當下載大約60-90%時,我得到了一個java.io.IOException「意外的流結束」錯誤。我不明白如何解決它,它讓我發瘋。

編輯:如果某人能夠在手機上成功下載文件,至少可以測試它嗎?這將允許我確定問題是我的手機還是代碼。

try { 
    URL url = new URL(full_url); 
    conexion = (URLConnection)url.openConnection(); 

    conexion.setReadTimeout(20000); 
    conexion.connect(); 
    File file = new File(root.getAbsolutePath()+"/", fileName); 

    int lenghtOfFile = conexion.getContentLength(); 
    System.out.println("content-length-header is: " + lenghtOfFile); 
    InputStream input = conexion.getInputStream(); 

    OutputStream output = new FileOutputStream(file); 

    byte data[] = new byte[8192]; 
    long total = 0; 
    contentView.setTextViewText(R.id.status_text,"Downloading file " + (78 - GlobalData.missingFiles.size()) + " of " + 77); 
    int downloadProgress = (int)((total*100)/lenghtOfFile); 

    int lastProgressUpdate=0; 

    while ((count = input.read(data)) != -1) { 
     System.out.println("available bytes:" + input.available()); 
     total += count; 

     downloadProgress = (int)((total*100)/lenghtOfFile); 
     Log.e("totaltotal","" + (int)((total*100)/lenghtOfFile)); 

     output.write(data,0,count); 
     if(downloadProgress%20==0 && downloadProgress != lastProgressUpdate) { 
      notification.contentView.setProgressBar(R.id.status_progress, 100,downloadProgress, false); 
      notificationManager.notify(1,notification); 
      lastProgressUpdate=downloadProgress;  
     } 
     if(downloadProgress == 100){ 
      GlobalData.downloadFiles.add("" +fileName); 
      GlobalData.missingFiles.remove(fileName); 
     } 
    } 

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

    if(downloadProgress != 100){ 
     File temp_file = new File(root.getAbsolutePath()+"/", fileName); 
     try{ 
      if(temp_file.exists()){ 
       boolean del_main = temp_file.delete(); 
       Log.e("File","Does file exists: " + del_main); 
       Log.e("FilePath","PATH: " + temp_file.getAbsolutePath()); 
      }else{ 
       Log.e("File Exists NOT","NOT EXISTING"); 
      } 
     }catch(Exception e){ 
      Log.e("FileDelete","deleting is giving problems"); 
     } 
    } 
} catch (Exception e) { 
    Log.e("PRINTSTACK","STACK:" + e.getMessage()); 
    e.printStackTrace(); 
    System.out.println("Downloading didn't work"); 

    killService(); 
} 
+0

「root」指向什麼? –

+0

根指向SD卡中的文件夾 – bytebiscuit

回答

1

由於某種原因輸入流過早關閉。通常這是因爲一次輸入流被多次讀取,但我猜這不是這種情況,即使你由於某種原因在比我們在這裏看到的範圍更廣的範圍內可用。

你說conexion = (URLConnection)url.openConnection();而不是預期的URLConnection conexion = url.openConnection();。請確保您不要嘗試兩次獲取輸入流。

我看到的唯一另外一件事很奇怪,那就是你直接使用來自conexion.getInputStream()的inputstream。嘗試將其封裝在緩衝輸入流中,例如:

InputStream input = new BufferedInputStream(connexion.getInputStream());