安卓存储位置通常有两大类,一类是用户随意指定,这个需要配置权限,高版本安卓中还需要用代码获得权限,这种存储在 APP 卸载后,不会随之删除。
另一类存储是存储在特定的位置,并不需要在 AndroidManifest.xml 中配置权限,在 APP 卸载后,或者用户清除该 APP 的数据后,这些存储文件都会被删除。
本文讲的第二类。
一、如何获得这类目录的路径
使用 getFilesDir()、getCacheDir(),以 getFilesDir() 为例,这个目录是类似:/data/data/com.itpow.test/files
二、读取这个目录下有哪些文件
示例,选取以 itpow 开头的文件。File file = new File(getFilesDir().getPath());
File[] fs = file.listFiles(new FileFilter() {
@Override
public boolean accept(File pathname) {
if (pathname.getName().startsWith("itpow")) {
return true;
}
else {
return false;
}
}
});
三、读取某一文件的内容
使用 FileInputStream,注意,Input 是读。try {
FileInputStream fis = openFileInput(f.getName());
byte[] buffer = new byte[fis.available()];
fis.read(buffer);
String s = new String(buffer);
fis.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
四、写入某一文件
使用 FileOutputStream,注意 Output 是写。try {
FileOutputStream fos = openFileOutput(filePath, MODE_PRIVATE);
fos.write(s);
fos.close();
} catch (FileNotFoundException e) {
result = false;
e.printStackTrace();
} catch (IOException e) {
result = false;
e.printStackTrace();
}
五、删除文件File f = new File(getFilesDir().getPath() + "/" + fileName);
f.delete();