【问题标题】:Downloading a document on android在安卓上下载文件
【发布时间】:2017-07-19 18:33:55
【问题描述】:

我想从我在网上抓取的链接下载文档,我有一个 listview 监听器,所以当我按下列表中的一个项目时,它会返回一个 url,我设置了它,所以 getLink 将是我要下载并设置的pdf文件的链接filenametoo。

getLink = http://www.phivolcs.dost.gov.ph/images/Flyer-eq-and-eq-hazards.pdf
filename = Flyer-eq-and-eq-hazards.pdf

所以我在我的 listview 侦听器中调用它,它假设可以下载但它不工作。 new DownloadFile().execute(getLink, filename);

我有像java.io.IOException: open failed: ENOENT (No such file or directory)这样的错误

主内

private class DownloadFile extends AsyncTask<String, Void, Void>{

   @Override
   protected Void doInBackground(String... strings) {
       String fileUrl = strings[0];   // -> getLink = http://www.phivolcs.dost.gov.ph/images/Flyer-eq-and-eq-hazards.pdf
       String fileName = strings[1];  // -> Flyer-eq-and-eq-hazards.pdf
       String extStorageDirectory = Environment.getDataDirectory().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;
   }
}

下载文件

package com.example.boneyflesh.homepage;


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.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();
        }
    }

  }

清单

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.example.boneyflesh.homepage">

<!--
     The ACCESS_COARSE/FINE_LOCATION permissions are not required to use
     Google Maps Android API v2, but you must specify either coarse or fine
     location permissions for the 'MyLocation' functionality. 
-->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></uses-permission>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" ></uses-permission>
<uses-permission android:name="android.permission.READ_PHONE_STATE"></uses-permission>


<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme"
    tools:ignore="AllowBackup">
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <!--
         The API key for Google Maps-based APIs is defined as a string resource.
         (See the file "res/values/google_maps_api.xml").
         Note that the API key is linked to the encryption key used to sign the APK.
         You need a different API key for each encryption key, including the release key that is used to
         sign the APK for publishing.
         You can define the keys for the debug and release targets in src/debug/ and src/release/. 
    -->
    <meta-data
        android:name="com.google.android.geo.API_KEY"
        android:value="@string/google_maps_key" />

    <activity
        android:name=".MapsActivity"
        android:label="@string/title_activity_maps" />
    <!--
 ATTENTION: This was auto-generated to add Google Play services to your project for
 App Indexing.  See https://g.co/AppIndexing/AndroidStudio for more information.
    -->
    <meta-data
        android:name="com.google.android.gms.version"
        android:value="@integer/google_play_services_version" />

    <activity android:name=".GeohazardResults" />
    <activity android:name=".MineralResults" />
    <activity android:name=".LandformResults" />
    <activity android:name=".Downloads"></activity>
</application>


编辑

我打电话给useFileAsyncTask(); 然后我收到一个错误FATAL EXCEPTION: AsyncTask #1

构造函数

protected void useFileAsyncTask() {
    DownloadFile task = new DownloadFile(this);
    task.execute();
}

异步任务

private class DownloadFile extends AsyncTask<String, Void, Void>{

   private Context myContextRef;

   public DownloadFile(Context context) {
       myContextRef = context;
   }


   @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 = myContextRef.getFilesDir().toString();
       //String extStorageDirectory = Environment.getDataDirectory().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(getLink, pdfFile);
       return null;
   }
   }

downloadFile 保持不变。

【问题讨论】:

    标签: android-studio android-asynctask download httpurlconnection fileinputstream


    【解决方案1】:

    换行

    String extStorageDirectory = Environment.getDataDirectory().toString();
    

    String extStorageDirectory = context.getFilesDir().toString();
    

    其中context 是您需要提供给AsyncTaskContext

    Environment.getDataDirectory() 是系统范围的用户数据目录,您不能在其中创建文件,而ontext.getFilesDir() 是您的应用程序的数据目录,您可以在其中创建文件。

    【讨论】:

    • 抱歉,我不太熟悉 AsyncTask 试图将其更改为 String extStorageDirectory = context.getFilesDir().toString(); 说无法解析符号“上下文”我的选项是创建一个局部变量、字段、参数和引用。我该怎么办?
    • 您需要将Context 加入您的AsyncTask - 有几种方法可以做到这一点,但您可以在 Stack Overflow 上的 getting context in AsyncTask 找到一种与 AsyncTask 一起使用的方法。
    • 您的代码使用AsyncTask。它是 DownloadFile 类的基类。您需要将Context 添加到DownloadFile 的构造函数中。
    • 我会编辑我的代码供您检查,我不知道我这样做是否正确。
    • 不,我没有下载文件,而是创建了browser intent,所以每次我点击链接时,它都会打开浏览器,当有人发布我的答案时,我仍然会执行此操作可以得到。
    猜你喜欢
    • 1970-01-01
    • 2015-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多