【问题标题】:FileNotFoundException when using getExternalStoragePublicDirectory使用 getExternalStoragePublicDirectory 时出现 FileNotFoundException
【发布时间】:2016-11-09 14:14:26
【问题描述】:

我有这个从网上下载文件的代码。它适用于有 SD 卡的手机,但我在没有 SD 卡的手机上对其进行了测试,但出现以下错误:

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

我该如何解决这个问题?

【问题讨论】:

  • 该设备运行 Android 6.0?
  • this code for downloading a file from the net. 无关。您的代码尝试在文件系统上创建一个文件。

标签: android filenotfoundexception android-file android-external-storage


【解决方案1】:

您可能想使用getExternalStorageDirectory。详情请查看文档:https://developer.android.com/reference/android/os/Environment.html

【讨论】:

    【解决方案2】:

    Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES)即使设备没有sd卡也无效,它会一直存在。请检查您的文件,它是否存在(在File 类中使用exists 方法)?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-03
      • 1970-01-01
      相关资源
      最近更新 更多