Your data storage options are the following:
-
Shared Preferences
- Store private primitive data in key-value pairs. Internal Storage
- Store private data on the device memory. External Storage
- Store public data on the shared external storage. SQLite Databases
- Store structured data in a private database. Network Connection
Store data on the web with your own network server.
Using the Internal Storage
openFileOutput()FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(string.getBytes());
fos.close();
getCacheDir()
缓存目录,系统内部存储比较少的时候会删除一些文件,需要保证缓存占用空间在一个合适的大小,删除APP时缓存目录会随着删除。
getFilesDir()
Gets the absolute path to the filesystem directory where your internal files are saved.
getDir()
Creates (or opens an existing) directory within your internal storage space.
deleteFile()
Deletes a file saved on the internal storage.
fileList()
Returns an array of files currently saved by your application.
Using the External Storage
/* 检测外部存储是否可以读写 */
public boolean isExternalStorageWritable() {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
return true;
}
return false;
}
/* 检测外部存储是否可读 */
public boolean isExternalStorageReadable() {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state) ||
Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
return true;
}
return false;
}
getExternalStoragePublicDirectory()
public File getAlbumStorageDir(String albumName) {
// Get the directory for the user's public pictures directory.
File file = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), albumName);
if (!file.mkdirs()) {
Log.e(LOG_TAG, "Directory not created");
}
return file;
}
Hiding your files from the Media Scanner
如果想要对系统Media扫描隐藏某个目录,在目录下面创建空文件,并命名为".nomedia"即可
getExternalFilesDir()
如果想处理一些不被其他APP访问的文件,可以使用getExternalFilesDir(),系统Media不会扫描这个目录,因此不要存放一些希望被扫描到的文件。随着APP的删除而删除。
getExternalCacheDir()
外部存储上的缓存目录,随着APP的删除而删除。
ContextCompat.getExternalFilesDirs()
ContextCompat.getExternalCacheDirs()
如果有额外的存储可以使用该方法。