我制作了一个 android 应用程序,用于通过在我的代码中集成 pdfViewer 库来查看从 URL 获取的 Pdf 文件。首先应用程序将文件从 Web 下载到外部 sd 卡,然后从那里使用 PdfViewer 库打开应用程序。如果文件工作正常大小很小,但如果 pdf 文件包含图像并且大小更大,则 sdcard 中显示的下载文件大小为 0kb。有人可以帮我弄清楚为什么会这样吗?
以下是java代码:
public class MainActivity extends Activity {
static Context applicationContext;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
applicationContext = getApplicationContext();
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
File folder = new File(extStorageDirectory, "pdfDownloads");
folder.mkdir();
File file = new File(folder, "android.pdf");
try {
if(!file.exists()) {
file.createNewFile();
}
} catch (IOException e1) {
e1.printStackTrace();
}
boolean downloadFile = downloadFile("http://www.irs.gov/pub/irs-pdf/fw4.pdf", file);
if (file!=null && file.exists() && file.length() > 0){
Intent intent = new Intent(this, com.example.soniapdf.Second.class);
intent.putExtra(PdfViewerActivity.EXTRA_PDFFILENAME,
file.getAbsolutePath());
startActivity(intent);
}
}
public static boolean downloadFile(String fileUrl, File directory) {
try {
FileOutputStream f = new FileOutputStream(directory);
URL u = new URL(fileUrl);
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
InputStream in = c.getInputStream();
byte[] buffer = new byte[1024];
int len = 0;
//
int fileLength = c.getContentLength();
long total = 0;
//
Toast.makeText(applicationContext, "Downloading PDF...", 2000).show();
while ((len = in.read(buffer)) > 0) {
total += len;
//Toast.makeText(applicationContext, "Downloading PDF: remaining " + (fileLength / total )+ "%", 1).show();
f.write(buffer, 0, len);
}
f.close();
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
}