外部存储
(1)特点:外部存储设备,SD卡
(2)存储位置:通常 mnt/sdcard 不同的厂商设备可能路径不同
需要在程序中找外部存储路径
(3)存取方式
存数据:
String state = Environment.getExternalStorageState();//取外部设备状态
if(state.equals(Environment.MEDIA_MOUNTED)){
File SDPath = Environment.getExternalStorageDirectory();//获取SD卡的目录
File file = new File(SDPath, "data.txt") ; //创建实际存储文件对象
FileOutputStream fos = null;
BufferedWriter writer = null;
String content = "HelloWorld!";
try {
fos = new FileOutputStream(file); //创建流对象
writer = new BufferedWriter(new OutputStreamWriter(fos));
writer.write(content);
} catch (Exception e) {
e.printStackTrace();
} finally{
try {
if(writer!= null)
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
取数据:
String state = Environment.getExternalStorageState();
if(state.equals(Environment.MEDIA_MOUNTED)){
File SDPath = Environment.getExternalStorageDirectory();//获取SD卡的目录
File file = new File(SDPath, "data.txt") ; //创建实际存储文件对象
FileInputStream fis = null;
BufferedReader reader = null;
String content = "";
try {
fis = new FileInputStream (file); //创建流对象
reader = new BufferedReader (new InputStreamReader(fis));
content = reader.readLine();
} catch (Exception e) {
e.printStackTrace();
} finally{
try {
if(reader!= null)
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
注意:进行外部存储需要得到外部设备访问权限
在AndroidMenifest.xml文件中需要对SD卡的访问权限进行声明。
此声明应置于节点之间,节点之外。
<uses-permission android:name=”android.permission.WRITE_EXTERNAM_STORAGE”/>
<uses-permission android:name=”android.permission.READ_EXTERNAM_STORAGE”/>
<uses-permission android:name=”android.permission.MOUNT_UNMOUNT_FILESYSTEMS”/>