【发布时间】:2014-09-04 14:06:11
【问题描述】:
我正在尝试编写一个应用程序来从 URL 下载 PDF,将它们存储在 SD 上,然后由 Adobe PDF 阅读器或其他应用程序(能够打开 PDF)打开。
到目前为止,我已经“成功下载并存储在 SD 卡上”(但每次我尝试使用 PDF 阅读器打开 PDF 时,阅读器都会崩溃并说出现意外错误),例如,@987654321 @
这是我的下载器的代码:
//........code set ui stuff
//........code set ui stuff
new DownloadFile().execute(fileUrl, fileName);
private class DownloadFile extends AsyncTask<String, Void, Void>{
@Override
protected Void doInBackground(String... strings) {
String fileUrl = strings[0]; // -> http://maven.apache.org/maven-1.x/maven.pdf
String fileName = strings[1]; // -> maven.pdf
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
File folder = new File(extStorageDirectory, "testthreepdf");
folder.mkdir();
File pdfFile = new File(folder, fileName);
try{
pdfFile.createNewFile();
}catch (IOException e){
e.printStackTrace();
}
FileDownloader.downloadFile(fileUrl, pdfFile);
return null;
}
}
public class FileDownloader {
private static final int MEGABYTE = 1024 * 1024;
public static void downloadFile(String fileUrl, File directory){
try {
URL url = new URL(fileUrl);
HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
urlConnection.connect();
InputStream inputStream = urlConnection.getInputStream();
FileOutputStream fileOutputStream = new FileOutputStream(directory);
int totalSize = urlConnection.getContentLength();
byte[] buffer = new byte[MEGABYTE];
int bufferLength = 0;
while((bufferLength = inputStream.read(buffer))>0 ){
fileOutputStream.write(buffer, 0, bufferLength);
}
fileOutputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
在调试模式下,我可以看到应用下载它并将此 PDF 存储在 /storage/sdcard/testpdf/maven.pdf 上。但是,我猜该文件可能在下载过程中以某种方式损坏,因此无法正常打开...
这是我打算如何用另一个阅读器应用程序打开它的代码:
File pdfFile = new File(Environment.getExternalStorageDirectory() + "/testthreepdf/" + fileName); // -> filename = maven.pdf
Uri path = Uri.fromFile(pdfFile);
Intent pdfIntent = new Intent(Intent.ACTION_VIEW);
pdfIntent.setDataAndType(path, "application/pdf");
pdfIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
try{
startActivity(pdfIntent);
}catch(ActivityNotFoundException e){
Toast.makeText(documentActivity, "No Application available to view PDF", Toast.LENGTH_SHORT).show();
}
【问题讨论】:
-
byte[] buffer = new byte[MEGABYTE];这条线是什么意思?它是否为缓冲区分配了 1 GB 的空间?
标签: android pdf download httpurlconnection fileinputstream