【问题标题】:Failed to download pdf file下载pdf文件失败
【发布时间】:2017-11-17 12:52:54
【问题描述】:

我想下载这个pdf文件

https://scholar.najah.edu/sites/default/files/book/dllt-lhwy-wlrmz-fy-lfwlklwr-lshby.pdf

我正在使用此代码下载 pdf 文件,它适用于许多文件,但它在上述 pdf 文件上失败

    public void downloadFile(@NonNull String urlStr, @NonNull String fullFilePath,
                         @NonNull DownloadListener downloadListener) {
    cancelStatus = false;
    InputStream is = null;
    File ffPath = null;
    FileOutputStream fos = null;
    try {
        downloadListener.onProgress(0);
        URL url = new URL(urlStr);
        URLConnection conexion = url.openConnection();
        conexion.setReadTimeout(2000000);
        conexion.setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_5_8; en-US) AppleWebKit/532.5 (KHTML, like Gecko) Chrome/4.0.249.0 Safari/532.5");
        System.setProperty("http.agent", "");
        conexion.connect();
        int lenghtOfFile = conexion.getContentLength();
        if (lenghtOfFile <= 0) lenghtOfFile = 1;
        is = url.openStream();
        ffPath = new File(fullFilePath);
        fos = new FileOutputStream(ffPath);
        int count = 0;
        long total = 0;
        int progress = 0;
        byte data[] = new byte[1024];
        while ((count = is.read(data)) != -1) {
            if (cancelStatus == true) {
                break;
            }
            total += count;
            int progress_temp = (int) total * 100 / lenghtOfFile;
            if (progress != progress_temp) {
                progress = progress_temp;
                downloadListener.onProgress(progress >= 0 && progress <= 100 ? progress : 0);
            }
            fos.write(data, 0, count);
            cancelStatus = downloadListener.onPacketDownloaded(total, lenghtOfFile);
        }
        if (is != null) is.close();
        if (fos != null) fos.close();

        if (lenghtOfFile <= 1) {
            downloadListener.onComplete();
        } else if (ffPath.length() < lenghtOfFile) {
            if (cancelStatus) {
                downloadListener.onCancel();
            } else {
                downloadListener.onError();
            }

        } else if (ffPath.length() >= lenghtOfFile) {
            downloadListener.onComplete();
        }
        if (cancelStatus == true) {
            if (ffPath != null) ffPath.delete();
        }
    } catch (MalformedURLException e) {
        try {
            if (is != null) is.close();
            if (fos != null) fos.close();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        if (ffPath != null) ffPath.delete();
        downloadListener.onError();
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (FileNotFoundException e) {
        try {
            if (is != null) is.close();
            if (fos != null) fos.close();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        if (ffPath != null) ffPath.delete();
        downloadListener.onError();
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        try {
            if (is != null) is.close();
            if (fos != null) fos.close();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        if (ffPath != null) ffPath.delete();
        downloadListener.onError();
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

问题是count = is.read(data)返回-1并在一个循环后从while循环中断,文件大约345 kb
请帮忙

【问题讨论】:

  • the problem is count = is.read(data) return -1 and break from while loop。真的吗?你怎么知道的?如果 cancelStatus==true,循环也会停止。将一些日志语句放入其中,以便您更好地了解发生了什么。此外,还不清楚downloadListener 是什么。以及从哪里调用 downloadFile()。

标签: java android download stream inputstream


【解决方案1】:

/** *下载文件也使用下载文件并保存到手机中 * * @param fileURL 包含文件地址 * @param fileName 包含文件名 */

public void DownloadFile(String fileURL, String fileName) {
    try {
        String RootDir = Environment.getExternalStorageDirectory()
                + File.separator + "Cards List";
        File RootFile = new File(RootDir);
        RootFile.mkdir();
        // File root = Environment.getExternalStorageDirectory();
        java.net.URL u = new URL(fileURL);
        HttpURLConnection c = (HttpURLConnection) u.openConnection();
        c.setRequestMethod("GET");
        c.setDoOutput(true);
        c.connect();
        FileOutputStream f = new FileOutputStream(new File(RootFile,
                fileName + " abc " + ".pdf"));
        InputStream in = c.getInputStream();
        byte[] buffer = new byte[1024];
        int len1 = 0;

        while ((len1 = in.read(buffer)) > 0) {
            f.write(buffer, 0, len1);
        }
        f.close();


    } catch (Exception e) {

        Log.d("Error....", e.toString());
    }

} // used to download the file from server

class ProgressBack extends AsyncTask<String, Void, Void> {
    ProgressDialog PD;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        PD = ProgressDialog.show(MainActivity.this, null, "Please Wait ...", true);
        PD.setCancelable(true);
    }

    @Override
    protected Void doInBackground(String... params) {
        DownloadFile("https://scholar.najah.edu/sites/default/files/book/dllt-lhwy-wlrmz-fy-lfwlklwr-lshby.pdf",
                "Cards List"); // calling DownloadFile
        return null;
    }

    @Override
    protected void onPostExecute(Void aVoid) {
        super.onPostExecute(aVoid);
        PD.dismiss();
        Toast.makeText(MainActivity.this, "Download Completed", Toast.LENGTH_SHORT).show();
    }
}

【讨论】:

  • 使用上面的代码下载文件。文件将保存在您的设备上。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-16
  • 2021-03-01
相关资源
最近更新 更多