问题描述
我想创建一个 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.
}
有更好的方法吗?
解决方法
也许你可以尝试这样的事情:
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,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 和运行时请求权限。