Android内存和SD卡的数据存取
内存
向内存存取数据,不需要任何权限
效果图
存
private String fileName = "test.txt";
public void saveToROM(View view) {
File file = new File(getFilesDir(), fileName);
try {
FileOutputStream fos = new FileOutputStream(file);
String str = "这是我写入内存的数据";
fos.write(str.getBytes());
fos.close();
Toast.makeText(this, "保存到内存成功", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(this, "保存到内存失败", Toast.LENGTH_SHORT).show();
}
}
取
private String fileName = "test.txt";
public void readFromROM(View view) {
File file = new File(getFilesDir(), fileName);
try {
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
String text = br.readLine();
br.close();
Toast.makeText(this, "读取:\n" + text, Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
}
保存成功以后,可以在data/data/包名/files
下看到文件
SD卡
保存到SD卡和保存到内存基本一样,只不过存储路径不一样,需要SD的存取权限,另外需要注意的是有的设备可能没有SD卡。
权限
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
存
private String fileName = "test.txt";
public void saveToSD(View view) {
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
// sd卡可用
File file = new File(Environment.getExternalStorageDirectory(), fileName);
try {
FileOutputStream fos = new FileOutputStream(file);
String str = "这是我写入SD卡的数据";
fos.write(str.getBytes());
fos.close();
Toast.makeText(this, "保存到SD卡成功", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(this, "保存到SD卡失败", Toast.LENGTH_SHORT).show();
}
} else {
// 当前不可用
Toast.makeText(this, "SD卡不可用", Toast.LENGTH_SHORT).show();
}
}
取
private String fileName = "test.txt";
public void readFromSD(View view) {
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
// SD卡可用
File file = new File(Environment.getExternalStorageDirectory(), fileName);
try {
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
String text = br.readLine();
br.close();
Toast.makeText(this, "读取:\n" + text, Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
} else {
// SD卡不可用
Toast.makeText(this, "SD卡不可用", Toast.LENGTH_SHORT).show();
}
}