1

私はネットからファイルをダウンロードするためのこのコードを持っています。これは、SDカードを持っている携帯電話で正常に動作しますが、私はSDカードを持っていると私は、次のエラーを得ていない携帯電話でそれをテストしてみた:getExternalStoragePublicDirectoryを使用した場合のFileNotFoundException

java.io.FileNotFoundException /storage/emulated/0/Movies/65656s5d.mp4 open failed :ENONET (no such file or directory) 

これはdoInBackGroundで私のコードです:

InputStream input = null; 
OutputStream output = null; 
HttpURLConnection connection = null; 
try { 
    URL url = new URL(sUrl[0]); 
    connection = (HttpURLConnection) url.openConnection(); 
    connection.connect(); 

    // expect HTTP 200 OK, so we don't mistakenly save error report 
    // instead of the file 
    if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) { 
     return "Server returned HTTP " + connection.getResponseCode() + " " 
       + connection.getResponseMessage(); 
    } 

    // this will be useful to display download percentage 
    // might be -1: server did not report the length 
    int fileLength = connection.getContentLength(); 

    // download the file 
    input = connection.getInputStream(); 

    long number = (long) Math.floor(Math.random() * 9000000000L) + 1000000000L; 
    String destPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES) 
      + File.separator+number + ".mp4"; 
    output = new FileOutputStream(destPath); 

    byte data[] = new byte[4096]; 
    long total = 0; 
    int count; 
    while ((count = input.read(data)) != -1) { 
     // allow canceling with back button 
     if (isCancelled()) { 
      input.close(); 
      return null; 
     } 
     total += count; 
     // publishing the progress.... 
     if (fileLength > 0) // only if total length is known 
      publishProgress((int) (total * 100/fileLength)); 
     output.write(data, 0, count); 
    } 
    return "ok"; 
} catch (Exception e) { 
    Log.v("this",e.getMessage()); 
    return e.toString(); 
} finally { 
    try { 
     if (output != null) 
      output.close(); 
     if (input != null) 
      input.close(); 
    } catch (IOException ignored) { 
     Log.v("this",ignored.getMessage()); 
     return ignored.toString(); 
    } 

    if (connection != null) 
     connection.disconnect(); 
} 

どうすればこの問題を解決できますか?

+0

そのデバイスはAndroid 6.0を実行していますか? – greenapps

+0

'ネットからファイルをダウンロードするためのこのコード.'無関係。あなたのコードは、ファイルシステム上にファイルを作成しようとします。 – greenapps

答えて

-1

Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES)でもデバイスにはSDカードがない場合でも、それは常にそこに存在します。あなたのファイルをチェックしてください、それは存在する(Fileクラスに存在するメソッドを使用して)?

関連する問題