Streetboy Streetboy - 4 months ago 14
Java Question

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.

Answer

Put

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

in your AndroidManifest.xml

Comments