无法下载pdf文件

时间:2017-11-17 12:52:55

标签: java android download stream inputstream

我想下载此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
请帮忙

1 个答案:

答案 0 :(得分:0)

/ **      *使用的下载文件也下载文件并保存到手机中      *      * @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();
    }
}