在android上下载文档

时间:2017-02-28 17:02:58

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

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

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)

等错误

insideMain

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;
   }
}

downloadFile

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

Asynktask

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保持不变。

1 个答案:

答案 0 :(得分:0)

更改行

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

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

context是您需要提供给Context的{​​{1}}。

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