下载 PDF 文件并保存到 SD 卡

4
我想下载并保存pdf文件到内部存储器。以下是我正在使用的代码:
我从其他类中调用我的方法:
new Thread(new Runnable() {
    public void run() {

        new Main().downloadPdfContent("http://people.opera.com/howcome/2005/ala/sample.pdf");

    }
  }).start();

方法看起来像这样:

public void downloadPdfContent(String urlToDownload){

    URLConnection urlConnection = null;

    try{

        URL url = new URL(urlToDownload);

        //Opening connection of currrent url

        urlConnection = url.openConnection();
        urlConnection.connect();

        //int lenghtOfFile = urlConnection.getContentLength();


    String PATH = Environment.getExternalStorageDirectory() + "/1/";

    File file = new File(PATH);
    file.mkdirs();
    File outputFile = new File(file, "test.pdf");
    FileOutputStream fos = new FileOutputStream(outputFile);

    InputStream is = url.openStream();


    byte[] buffer = new byte[1024];

    int len1 = 0;

    while ((len1 = is.read(buffer)) != -1) {
        fos.write(buffer, 0, len1);
    }

    fos.close();
    is.close();

   System.out.println("--pdf downloaded--ok--"+urlToDownload);

    }catch (Exception e) {
        // TODO: handle exception
        e.printStackTrace();

    }

}

我在网上找到了一个PDF文件的链接: http://people.opera.com/howcome/2005/ala/sample.pdf 但是当我运行这行代码时出现了异常: urlConnection.connect(); 异常信息为: java.net.UnknownHostException: people.opera.com 我无法确定问题出在哪里。也许有人可以帮忙看一下。
谢谢。
3个回答

4
放置
    <uses-permission android:name="android.permission.INTERNET"/>

在你的AndroidManifest.xml文件中。

1
跟随以下步骤:

1)声明文件名

。内容涉及编程,保留HTML格式,不做解释。
String fileName;
    //for image
    fileName = "matchfine1.png";
    //for pdf
    fileName = "samplepdf.pdf";

2)调用方法以启动下载过程。

startDownload(fileName);

3) 定义startDownload方法:

//for download file start
    private void startDownload(String filename) {
        String filedowname = filename;
        //for image
        String url = "http://farm1.static.flickr.com/114/298125983_0e4bf66782_b.jpg";
        //for pdf
        String url = "http://people.opera.com/howcome/2005/ala/sample.pdf";
        new DownloadFileAsync().execute(url,filedowname);
    }

4) 自动加载进度条:

@Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
            case DIALOG_DOWNLOAD_PROGRESS:
                mProgressDialog = new ProgressDialog(this);
                mProgressDialog.setMessage("Downloading file..");
                mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
                mProgressDialog.setCancelable(false);
                mProgressDialog.show();
                return mProgressDialog;
            default:
                return null;
        }
    }

5) 定义扩展AsyncTask的下载过程

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

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            showDialog(DIALOG_DOWNLOAD_PROGRESS);
        }

        @Override
        protected String doInBackground(final String... aurl) {

            try {

                File root = android.os.Environment.getExternalStorageDirectory();
                File dir = new File (root.getAbsolutePath() + "/Your_file_save_path/");
                if(dir.exists()==false) {
                    dir.mkdirs();
                }

                URL url = new URL(aurl[0]);
                String filename = aurl[1];
                URLConnection conexion = url.openConnection();
                conexion.connect();

                int lenghtOfFile = conexion.getContentLength();
                Log.d("ANDRO_ASYNC", "Lenght of file: " + lenghtOfFile);

                InputStream input = new BufferedInputStream(url.openStream());
                OutputStream output = new FileOutputStream(dir+"/"+filename);

                byte data[] = new byte[1024];

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

                output.flush();
                output.close();
                input.close();
            } catch (Exception e) {}
            return null;

        }
        protected void onProgressUpdate(String... progress) {
            Log.d("ANDRO_ASYNC", progress[0]);
            mProgressDialog.setProgress(Integer.parseInt(progress[0]));
        }

        @Override
        protected void onPostExecute(String unused) {
            dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
        }
    }
    //for download file end

6) 将“Your_file_save_path”替换为目录中的文件路径,然后下载并检查指定位置。


-1

我使用了相同的代码并得到了 Network.onThreadException 错误。但是,当我在我的oncreate()方法中使用这段代码后,我成功解决了这个问题。

if (android.os.Build.VERSION.SDK_INT > 9)    
{       
     StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
     StrictMode.setThreadPolicy(policy);
 }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接