简体   繁体   中英

Downloading pdf file and saving to SD card

I want to download and save pdf file to internal storage. Here is code that i am using:

I am calling my method from other class:

new Thread(new Runnable() {
    public void run() {

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

    }
  }).start();

Method look like this:

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();

    }

}

I found link of pdf on the web: http://people.opera.com/howcome/2005/ala/sample.pdf

However i get an exception on this line:

urlConnection.connect();

Exception: java.net.UnknownHostException: people.opera.com

I can't figure out what's wrong. Maybe someone could take a look.

Thanks.

Put

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

in your AndroidManifest.xml

Follow following steps :

1) Declare file name

String fileName;
    //for image
    fileName = "matchfine1.png";
    //for pdf
    fileName = "samplepdf.pdf";

2) Call method to invoke download process.

startDownload(fileName);

3) Define startDownload method:

//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) For auto loading 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) Define the download process extending 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) Replace "Your_file_save_path" by your file path in dir. and then download and check in the specified location.

I have used the same code and got Network.onThreadException Error .

But then after using this piece of code in my oncreate() method, I was able to resolve the issue.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM