【问题标题】:How to save file to external storage properly in Android?如何在 Android 中正确地将文件保存到外部存储?
【发布时间】:2021-04-10 00:33:16
【问题描述】:

我想创建一个 zip 文件并将其保存到外部存储中。任何外部文件夹都可以。旧方法是使用Environment.getExternalStorageDirectory(),但已被弃用。它在 API 30 上引发异常。新方法是使用 MediaStore.Downloads.EXTERNAL_CONTENT_URI,但这仅在 API 29 之后可用。所以基本上我需要使用 if 语句编写代码两次,如果我希望我的应用程序在所有 API 级别上工作:

if (Build.VERSION.SDK_INT >= 29) {
   // Do it the new way.
} else {
   // Do it the old way.
}

有没有更好的办法?

【问题讨论】:

  • It throws exception on API 30 不,不是全部。它提供了一个很好的 File 实例,就像以前一样。
  • 我得到了java.io.IOException: Operation not permitted,即使应用程序有WRITE_EXTERNAL_STORAGE 运行时权限。我做错了什么?
  • 我们不知道你做了什么。但是调用 getExternalStorageDirectory() 不会抛出异常。
  • 您找到解决方案了吗?

标签: android mediastore android-storage


【解决方案1】:

也许你可以试试这样的:

try {
        File yourFileToSave = /* You find your file to work with here */;

        File storedFile = new File(context.getCacheDir(), "storedFileName.jpg");
        storedFile.createNewFile();
        FileInputStream fis = new FileInputStream(yourFileToSave);
        byte[] data = new byte[(int) yourFileToSave.length()];
        BufferedInputStream bis = new BufferedInputStream(fis);
        bis.read(data,0,data.length);
        FileOutputStream fos = new FileOutputStream(storedFile);
        fos.write(data);
        fos.flush();
        fos.close();

    } catch (IOException e) {
        e.printStackTrace();
    }

它类似于我用来存储位图的东西,但我必须为你稍微调整一下。这里的关键是使用 context.getCacheDir() 为您的应用程序找到一个合适的目录来存储文件。如果系统需要更多空间,则可以删除缓存目录中的文件,这可能会很好,因为您最终可能会得到很多从未使用过的存储文件,但如果您的文件很重要,您也许应该找到另一个位置,例如 context.getFilesDir() 或 getDataDir()。

别忘了在 AndroidManifest 中请求权限,同时也请求运行时权限。

【讨论】:

    猜你喜欢
    • 2011-12-14
    • 1970-01-01
    • 1970-01-01
    • 2021-04-14
    • 2023-03-10
    • 1970-01-01
    • 1970-01-01
    • 2012-10-21
    • 2011-10-10
    相关资源
    最近更新 更多