2011-11-21 67 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());