如何在Android中下载pdf文件? [英] How to download a pdf file in Android?

查看:413
本文介绍了如何在Android中下载pdf文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从网址下载一个pdf文件。
要查看pdf文件,我使用以下代码。

 文件文件=新建文件(/ sdcard / example .PDF); 

if(file.exists()){
Uri path = Uri.fromFile(file);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(path,application / pdf);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

try {
startActivity(intent);
}
catch(ActivityNotFoundException e){
Toast.makeText(OpenPdf.this,No Application Available to View PDF,
Toast.LENGTH_SHORT).show();
}
}

它正在工作,但如何获取pdf文件来自一个网址(例如 http://.../example.pdf )。我想从这个网址下载 pdf文件。请帮帮我。感谢提前。

解决方案

下载PDF的工作方式与下载任何其他二进制文件相同。


  1. 打开 HttpUrlConnection

  2. 使用连接的 getInputStream() 方法来读取文件。

  3. 创建一个 FileOutputStream 并写入输入流。

检查这篇文章,例如源代码。 / p>

I want to download a pdf file from an url. For viewing the pdf file I used the code below.

File file = new File("/sdcard/example.pdf");

if (file.exists()) {
    Uri path = Uri.fromFile(file);
    Intent intent = new Intent(Intent.ACTION_VIEW);
    intent.setDataAndType(path, "application/pdf");
    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

    try {
        startActivity(intent);
    } 
    catch (ActivityNotFoundException e) {
        Toast.makeText(OpenPdf.this, "No Application Available to View PDF",
            Toast.LENGTH_SHORT).show();
    }
}

It is working but how do I get the pdf file from an url (e.g http://.../example.pdf). I want to download the pdf file from this url. Please help me. Thanks in advance.

解决方案

Downloading a PDF works the same as downloading any other binary file.

  1. Open a HttpUrlConnection
  2. Use the connection's getInputStream() method to read the file.
  3. Create a FileOutputStream and write the inputstream.

Check this post for example source code.

这篇关于如何在Android中下载pdf文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆