下载文件时出现 InputStream 异常

InputStream Exception while downloading a file

我正在尝试从服务器下载 PPT 文件。 它以字节为单位。

但在调试时我注意到输入流抛出 FileNotFound 异常,而 运行.. 该文件确实存在于服务器上,这是我的代码,任何帮助将不胜感激。

public class DownloadFileAsync extends AsyncTask<String, String, String> {


@Override
protected String doInBackground(String... aurl) {
    int count;

    try {
        URL url = new URL(aurl[0]);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.addRequestProperty("Authorization", "Basic " + SharedPref.getAuthPrefValue());
        connection.addRequestProperty("Device", BaseApplication.getCurrentDevice().getDevice().toString());
        connection.addRequestProperty("DeviceId", BaseApplication.getCurrentDevice().getDeviceId());
        connection.connect();

        int lengthOfFile = connection.getContentLength();
        Log.d("ANDRO_ASYNC", "Length of file: " + lengthOfFile);

        InputStream input = new BufferedInputStream(url.openStream());
        File sdcardDest = new File(Environment.getExternalStorageDirectory(), "Availo");
        String finalDest = sdcardDest + File.separator + "Check1" + "." + "PPT";
        OutputStream output = new FileOutputStream(finalDest);

        byte data[] = new byte[1024];

        long total = 0;

        while ((count = input.read(data)) != -1) {
            total += count;
            publishProgress(""+(int)((total*100)/lengthOfFile));
            output.write(data, 0, count);
        }

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

    } catch (Exception e) {
        e.printStackTrace();
    }


    return null;
}

我在 Mac 上使用 Charles(类似于 windows 上的 fiddler)来查看我从服务器发送和接收的内容, 服务器没有 return 任何错误,尽管它显示了 6-7 秒的下载步骤,下载了大约 400 字节然后停止。

从输入流行抛出异常。

谢谢!

建议你看一下DownloadManager系统服务。它专为您的目的而设计:

(来自文档)

The download manager is a system service that handles long-running HTTP downloads. Clients may request that a URI be downloaded to a particular destination file. The download manager will conduct the download in the background, taking care of HTTP interactions and retrying downloads after failures or across connectivity changes and system reboots

虽然我同意 Muzikant 关于下载管理器的观点,
FileNotFoundException 通常在以下情况下抛出... 在本地设备上找不到文件...

您需要执行以下操作以确保它不会发生

File dest = new File(finalDest);

try{
    File parentDest = dest.getParentFile();
    if(!parentDest.exists()){
    parentDest.mkdirs(); //make all the directory structures needed
   }

if(!dest.exists()){
    dest.createNewFile();
}


OutputStream output = new FileOutputStream(dest);
//now you can use your file dest
//write data to it... 

}catch (Exception e){


}