簡體   English   中英

下載pdf文件並保存到SD卡

[英]Downloading pdf file and saving to SD card

我想下載並保存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

我無法弄清楚出了什么問題。 也許有人可以看看。

謝謝。

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

在AndroidManifest.xml中

請遵循以下步驟:

1)聲明文件名

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)對於自動加載progressBar:

@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)用dir中的文件路徑替換“Your_file_save_path”。 然后下載並檢查指定的位置。

我使用了相同的代碼並得到了Network.onThreadException錯誤

但是在我的oncreate()方法中使用這段代碼之后,我就能夠解決這個問題了。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM