下载文件时出现流错误?

时间:2011-11-21 00:50:52

标签: android

  

可能重复:
  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();
}

1 个答案:

答案 0 :(得分:1)

由于某种原因,输入流过早关闭。通常这是因为输入流被一次读取多次,但我猜这不是这里的情况,即使你出于某种原因conexion可用的范围比我们在这里看到的范围更广。

您说的是conexion = (URLConnection)url.openConnection();而不是预期的URLConnection conexion = url.openConnection();。请确保您不要尝试两次获取输入流。

我看到的另一件事我看起来很奇怪,就是你直接使用来自conexion.getInputStream()的输入流。尝试将其包装在缓冲的输入流中:

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