本文介绍了下载PDF文件并保存到SD卡的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想pdf文件下载并保存到内部存储。这里是code,我现在用:
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();
方法是这样的:
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格式的链接:
不过,我在这条线得到一个异常:
However i get an exception on this line:
urlConnection.connect();
例外:
的java.net.UnknownHostException:people.opera.com
我无法弄清楚什么是错的。也许有人可以看看。
I can't figure out what's wrong. Maybe someone could take a look.
感谢。
推荐答案
将
<uses-permission android:name="android.permission.INTERNET"/>
在你的AndroidManifest.xml
in your AndroidManifest.xml
这篇关于下载PDF文件并保存到SD卡的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!