问题描述
我试图写一个应用程序来从URL下载PDF文件,将它们存储在SD,然后由Adobe PDF阅读器或其他应用程序而以往任何时候都能够打开PDF打开。
直到如今,我可以成功地下载和创建SD文件存储(但每次当我尝试打开与Adobe或其他阅读器,阅读器崩溃的PDF说发生意外错误),例如,的
这里是code我下载:
//........code设置UI的东西
//........$c$c设置UI的东西
新DownloadFile()执行(fileUrl,文件名);
私有类DownloadFile扩展的AsyncTask<字符串,太虚,太虚> {
@覆盖
保护无效doInBackground(字符串...字符串){
串fileUrl =串[0]; // - > http://maven.apache.org/maven-1.x/maven.pdf
字符串文件名=串[1]; // - > maven.pdf
。字符串extStorageDirectory = Environment.getExternalStorageDirectory()的toString();
文件夹=新的文件(extStorageDirectory,testthreepdf);
folder.mkdir();
文件pdfFile =新的文件(文件夹中,文件名);
尝试{
pdfFile.createNewFile();
}赶上(IOException异常E){
e.printStackTrace();
}
FileDownloader.downloadFile(fileUrl,pdfFile);
返回null;
}
}
公共类FileDownloader {
私有静态最终诠释兆字节= 1024 * 1024;
公共静态无效downloadFile(字符串fileUrl,文件目录){
尝试 {
网址URL =新的URL(fileUrl);
HttpURLConnection的的URLConnection =(HttpURLConnection类)url.openConnection();
urlConnection.setRequestMethod(GET);
urlConnection.setDoOutput(真正的);
urlConnection.connect();
InputStream中的InputStream = urlConnection.getInputStream();
FileOutputStream中的FileOutputStream =新的FileOutputStream(目录);
INT totalSize = urlConnection.getContentLength();
byte []的缓冲区=新的字节[兆]
INT BufferLength中= 0;
而(量(bufferLength = inputStream.read(缓冲液))大于0){
fileOutputStream.write(缓冲液,0,BufferLength中);
}
fileOutputStream.close();
}赶上(FileNotFoundException异常E){
e.printStackTrace();
}赶上(MalformedURLException异常E){
e.printStackTrace();
}赶上(IOException异常E){
e.printStackTrace();
}
}
}
在调试模式下,我可以看到应用程序下载并阅读本存储在/storage/sdcard/testpdf/maven.pdf,但是,我想该文件可能会以某种方式在下载过程中被损坏,所以它不正常打开了。 ..
这里是code我怎么意图与其他阅读器应用程序中打开它:
文件pdfFile =新的文件(Environment.getExternalStorageDirectory()+/ testthreepdf /+文件名); // - >文件名= maven.pdf
URI路径= Uri.fromFile(pdfFile);
意图pdfIntent =新的意图(Intent.ACTION_VIEW);
pdfIntent.setDataAndType(道路,应用程序/ PDF格式);
pdfIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
尝试{
startActivity(pdfIntent);
}赶上(ActivityNotFoundException E){
Toast.makeText(documentActivity,没有应用程序可用来查看PDF,Toast.LENGTH_SHORT).show();
}
嗨问题是在FileDownloader类
urlConnection.setRequestMethod(GET);
urlConnection.setDoOutput(真正的);
您需要删除上面的两行,一切都将正常工作。请注明的问题,如果它工作正常回答。
附加工作code与截图。
MainActivity.java
包com.example.downloadread;
进口的java.io.File;
进口java.io.IOException异常;
进口android.app.Activity;
进口android.content.ActivityNotFoundException;
进口android.content.Intent;
进口android.net.Uri;
进口android.os.AsyncTask;
进口android.os.Bundle;
进口android.os.Environment;
进口android.view.Menu;
进口android.view.View;
进口android.widget.Toast;
公共类MainActivity延伸活动{
@覆盖
保护无效的onCreate(包savedInstanceState){
super.onCreate(savedInstanceState);
的setContentView(R.layout.activity_main);
}
@覆盖
公共布尔onCreateOptionsMenu(功能菜单){
//充气菜单;这增加了项目操作栏,如果它是present。
。getMenuInflater()膨胀(R.menu.main,菜单);
返回true;
}
公共无效下载(视图v)
{
新DownloadFile()执行(http://maven.apache.org/maven-1.x/maven.pdf,maven.pdf);
}
公共无效视图(View V)
{
文件pdfFile =新的文件(Environment.getExternalStorageDirectory()+/ testthreepdf /+maven.pdf); // - >文件名= maven.pdf
URI路径= Uri.fromFile(pdfFile);
意图pdfIntent =新的意图(Intent.ACTION_VIEW);
pdfIntent.setDataAndType(道路,应用程序/ PDF格式);
pdfIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
尝试{
startActivity(pdfIntent);
}赶上(ActivityNotFoundException E){
Toast.makeText(MainActivity.this,没有应用程序可用来查看PDF,Toast.LENGTH_SHORT).show();
}
}
私有类DownloadFile扩展的AsyncTask<字符串,太虚,太虚> {
@覆盖
保护无效doInBackground(字符串...字符串){
串fileUrl =串[0]; // - > http://maven.apache.org/maven-1.x/maven.pdf
字符串文件名=串[1]; // - > maven.pdf
。字符串extStorageDirectory = Environment.getExternalStorageDirectory()的toString();
文件夹=新的文件(extStorageDirectory,testthreepdf);
folder.mkdir();
文件pdfFile =新的文件(文件夹中,文件名);
尝试{
pdfFile.createNewFile();
}赶上(IOException异常E){
e.printStackTrace();
}
FileDownloader.downloadFile(fileUrl,pdfFile);
返回null;
}
}
}
FileDownloader.java
包com.example.downloadread;
进口的java.io.File;
进口java.io.FileNotFoundException;
进口java.io.FileOutputStream中;
进口java.io.IOException异常;
进口的java.io.InputStream;
进口java.net.HttpURLConnection中;
进口java.net.MalformedURLException;
进口的java.net.URL;
公共类FileDownloader {
私有静态最终诠释兆字节= 1024 * 1024;
公共静态无效downloadFile(字符串fileUrl,文件目录){
尝试 {
网址URL =新的URL(fileUrl);
HttpURLConnection的的URLConnection =(HttpURLConnection类)url.openConnection();
//urlConnection.setRequestMethod("GET);
//urlConnection.setDoOutput(true);
urlConnection.connect();
InputStream中的InputStream = urlConnection.getInputStream();
FileOutputStream中的FileOutputStream =新的FileOutputStream(目录);
INT totalSize = urlConnection.getContentLength();
byte []的缓冲区=新的字节[兆]
INT BufferLength中= 0;
而(量(bufferLength = inputStream.read(缓冲液))大于0){
fileOutputStream.write(缓冲液,0,BufferLength中);
}
fileOutputStream.close();
}赶上(FileNotFoundException异常E){
e.printStackTrace();
}赶上(MalformedURLException异常E){
e.printStackTrace();
}赶上(IOException异常E){
e.printStackTrace();
}
}
}
AndroidManifest.xml中
< XML版本=1.0编码=UTF-8&GT?;
<舱单的xmlns:机器人=http://schemas.android.com/apk/res/android
包=com.example.downloadread
安卓版code =1
机器人:VERSIONNAME =1.0>
<用途-SDK
安卓的minSdkVersion =14
机器人:targetSdkVersion =18/>
<使用-权限的Android:名称=android.permission.INTERNET对>< /使用-许可>
<使用-权限的Android:名称=android.permission.WRITE_EXTERNAL_STORAGE>< /使用-许可>
<使用-权限的Android:名称=android.permission.ACCESS_NETWORK_STATE>< /使用-许可>
<使用-权限的Android:名称=android.permission.READ_PHONE_STATE>< /使用-许可>
<应用
机器人:allowBackup =真
机器人:图标=@可绘制/ ic_launcher
机器人:标签=@字符串/ APP_NAME
机器人:主题=@风格/ AppTheme>
<活动
机器人:名称=com.example.downloadread.MainActivity
机器人:标签=@字符串/ APP_NAME>
<意向滤光器>
<作用机器人:名称=android.intent.action.MAIN/>
<类机器人:名称=android.intent.category.LAUNCHER/>
&所述; /意图滤光器>
< /活性GT;
< /用途>
< /舱单>
activity_main.xml
< RelativeLayout的的xmlns:机器人=http://schemas.android.com/apk/res/android
的xmlns:工具=http://schemas.android.com/tools
机器人:layout_width =match_parent
机器人:layout_height =match_parent
机器人:paddingBottom会=@扪/ activity_vertical_margin
机器人:以下属性来=@扪/ activity_horizontal_margin
机器人:paddingRight =@扪/ activity_horizontal_margin
机器人:paddingTop =@扪/ activity_vertical_margin
工具:上下文=MainActivity。>
<按钮
机器人:ID =@ + ID /按钮1
机器人:layout_width =match_parent
机器人:layout_height =WRAP_CONTENT
机器人:layout_alignParentLeft =真
机器人:layout_alignParentTop =真
机器人:layout_marginTop =15dp
机器人:文本=下载
机器人:的onClick =下载/>
<按钮
机器人:ID =@ + ID /按钮2
机器人:layout_width =match_parent
机器人:layout_height =WRAP_CONTENT
机器人:layout_alignParentLeft =真
机器人:layout_alignParentRight =真
机器人:layout_below =@ + ID /按钮1
机器人:layout_marginTop =38dp
机器人:文本=查看
机器人:的onClick =查看/>
< / RelativeLayout的>
I am trying to write an app to download pdfs from url, store them on sd, then open by adobe pdf reader or other apps which ever able to open the pdf.
untill now, i can "successfully download and create file store on sd" (but everytime when i try to open the pdf with adobe or other reader, reader crash and say unexpected error occurs), for example, http://maven.apache.org/maven-1.x/maven.pdf
here is the code for my downloader:
//........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();
}
}
}
in debug mode, i can see the app downloaded it and store this pdf on /storage/sdcard/testpdf/maven.pdf, however, i guess the file may be corrupted somehow during downloading, so it doesnt open up properly...
here is the code how i intent to open it with other reader app:
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();
}
Hi the problem is in FileDownloader class
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
You need to remove the above two lines and everything will work fine. Please mark the question as answered if it is working as expected.
Attaching the working code with screenshots.
MainActivity.java
package com.example.downloadread;
import java.io.File;
import java.io.IOException;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.view.Menu;
import android.view.View;
import android.widget.Toast;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void download(View v)
{
new DownloadFile().execute("http://maven.apache.org/maven-1.x/maven.pdf", "maven.pdf");
}
public void view(View v)
{
File pdfFile = new File(Environment.getExternalStorageDirectory() + "/testthreepdf/" + "maven.pdf"); // -> 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(MainActivity.this, "No Application available to view PDF", Toast.LENGTH_SHORT).show();
}
}
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;
}
}
}
FileDownloader.java
package com.example.downloadread;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
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();
}
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.downloadread"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="18" />
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
<uses-permission android:name="android.permission.READ_PHONE_STATE"></uses-permission>
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.downloadread.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<Button
android:id="@+id/button1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginTop="15dp"
android:text="download"
android:onClick="download" />
<Button
android:id="@+id/button2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_below="@+id/button1"
android:layout_marginTop="38dp"
android:text="view"
android:onClick="view" />
</RelativeLayout>
这篇关于从URL安卓下载PDF然后用一个PDF阅读器打开它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!