2017-03-27 5 views
0

ファイルをダウンロードしてデバイスのSDカードに保存します。私はこのためにgetExternalFilesDir()を使用しています。これはAndroidデベロッパーグループでも推奨されていますが、私のアプリを実行すると、両方の場所(SDカードと内部メモリ)にアプリケーションパッケージ用に作成されたディレクトリがありますが、内部メモリに保存されます。getExternalFilesDir()、Androidを使用してダウンロードしたファイルをSDカードに保存しようとしています

答えて

0

使用ダウン​​ロードするには、このスレッド:

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

    @Override 
    protected void onPreExecute() { 
     super.onPreExecute(); 
    } 

    @Override 
    protected String doInBackground(String... Url) { 
     int count; 
     try { 
      URL url = new URL(Url[0]); 
      URLConnection connection = url.openConnection(); 
      connection.connect(); 
      int fileLength = connection.getContentLength(); 
      String folder_main = "TEST1"; 
      File f = new File(Environment.getExternalStorageDirectory(), folder_main); 
      if (!f.exists()) { 
       f.mkdirs(); 
      } 
      int lenghtOfFile = connection .getContentLength(); 

      // input stream to read file - with 8k buffer 
      InputStream input = new BufferedInputStream(url.openStream(), 
        8192); 

      // Save the downloaded file 
      OutputStream output = new FileOutputStream(f + "/" 
        + movie_name_b); 
      byte data[] = new byte[1024]; 

      long total = 0; 

      while ((count = input.read(data)) != -1) { 
       total += count; 
       // publishing the progress.... 
       // After this onProgressUpdate will be called 
       publishProgress((int) (total * 100/fileLength)); 

       // writing data to file 
       output.write(data, 0, count); 
      } 
      // flushing output 
      output.flush(); 

      // closing streams 
      output.close(); 
      input.close(); 
     } 

     catch (Exception e) { 
      // Error Log 
      Log.e("Error", e.getMessage()); 
      e.printStackTrace(); 
     } 
     return null; 
    } 

    @Override 
    protected void onPostExecute(String file_url) { 
    } 
} 

実行します。

new DownloadFile().execute(URL_TO_DOWNLOAD); 

をそれはあなたのSDカードにフォルダ名のTest1を作成します。 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

+0

別の回答でも述べたとおりです。私もこれを試しましたが、うまくいかないようです。 'Environment.getExternalStorageDirectory()'と 'getExternalFilesDir()'はどちらもうまくいきましたが、ファイルを内部メモリに保存しています。 – Fragger

+0

あなたがチェックしているAPIバージョンは? –

0

Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)を使用して、SDカードのダウンロードディレクトリにファイルを保存することができます。

関連する問題