“内部存储”和“外部存储”这两个术语一开始可能会让人感到困惑,因为 Google 的意图与我们今天所期望和知道的不同 -当今使用的语言:“外部”并不一定意味着“SD 卡”。 This guy made a great article about the terminology confusion
根据您的意图,您可能希望使用 外部存储 概念。 Documentation 中对这些差异进行了很好的解释,但我将在此处简要介绍一下。
最后我会给你一个例子,但首先让我们了解一下基础知识:
内部存储
-
只有您的应用程序可以访问文件
- 卸载您的应用时会删除文件
- 文件始终可用(这意味着文件永远不会保存在可移动内存中)
外部存储
-
其他应用程序(包括文件管理器应用程序的任何变体,在您的情况下)完全可以读取文件
- 卸载应用时不一定会删除文件 - 稍后解释
- 不保证文件的可用性(可以被其他应用程序/可移动内存删除)
既然我们知道您需要外部存储,那么在开始之前需要做几件事:
-
需要权限(读/写)在您的
Manifest.xml 文件中,具体取决于您的需要:
<manifest ...>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
...
</manifest>
每个权限都是独立的,这意味着您不需要同时拥有这两个权限,例如,如果您只想读取文件而不是写入文件
示例时间!
在给定的方法中,我们将在根目录中保存一个文本文件。
感谢this article
public void writeFileExternalStorage() {
//Text of the Document
String textToWrite = "bla bla bla";
//Checking the availability state of the External Storage.
String state = Environment.getExternalStorageState();
if (!Environment.MEDIA_MOUNTED.equals(state)) {
//If it isn't mounted - we can't write into it.
return;
}
//Create a new file that points to the root directory, with the given name:
File file = new File(getExternalFilesDir(null), filenameExternal);
//This point and below is responsible for the write operation
FileOutputStream outputStream = null;
try {
file.createNewFile();
//second argument of FileOutputStream constructor indicates whether
//to append or create new file if one exists
outputStream = new FileOutputStream(file, true);
outputStream.write(textToWrite.getBytes());
outputStream.flush();
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
我想具体回答您的一些问题:
我需要在 android studio 中创建这些文件夹作为添加文件夹吗?还是我需要从代码中创建它?
绝对不是通过 Android Studio。这些是您的项目文件夹,包含您的代码。方法上面已经提到了。
我找不到包含我的应用名称的文件夹以及其中的数据库和图像文件夹...我做错了什么?
如您之前提到的,可能将您的文件保存为内部存储文件/将它们保存为项目文件夹 - 而那些不会(也不应该)显示出来。
有用的知识
有两种类型的目录:公共和私有。
私人
- 媒体商店无法访问
- 卸载应用时删除文件
- 由
getExternalFilesDir(...) 方法检索
示例:WhatsApp 目录(在我的手机中)位于根级别。调用它是:getExternalFilesDir("WhatsApp/...")
公共(下载/电影/图片库)
- 文件由MediaStore 扫描
- 由
Environment.getExternalStoragePublicDirectory(...) 方法检索
示例: 获取 Documents 文件夹如下所示:Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS)