Android数据存储与IO之三(File存储之ExternalStorage)
当程序利用Context提供的openFileinput或者openFileOutput打开文件输入、输出流时,程序打开的都是/data/data/<package>/files/下的文件,这样存储的空间可能有限并且保存在/data/data/<package>目录中文件,会在卸载应用程序时被删除掉,这可能会带来一些问题,为了更好的存取应用程序的大文件数据,应用程序需要读、写SD卡上的文件。读写SD卡的文件步骤如下所示:
1.调用Environment的getExternalStorageState().方法判断手机是否插入了SD卡并且具有读写SD卡的权限具体如下
当Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED为true时说明已经插入SD卡并且具有读写权限,注意,这里的读写权限需要在编写程序中添加,具体方法是在AndroidManifest.xml文件中添加
<uses-permission android:name="android.permission.MOUNT_FORMAT_FILESYSTEMS"/>//具有创建与删除的权限
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>//具有修改的权限
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />//具有读取的权限
来获得权限
2.调用Environment的getExternalStorageDirectory()方法来获取SD开的目录
3.使用FileInputStream、FileOutputStream、FileReader、FileWriter读写SD卡中的文件,其方法与读写本机内存中的文件方法类似
最后同样的,一定要记得关闭IO流
下面我们利用SD卡进行简单的文件读写
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
test08 = (TextView) findViewById(R.id.TEST);
fileName = "/test08.txt";
write("hhhhhhhhhhhhhhhhhhhhhhhhhhhhh");
read();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void write(String str){
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){//判断当前状态
File sdCardDir=Environment.getDataDirectory();//获得SD卡路径
try {
File file=new File(sdCardDir.getCanonicalPath()+fileName);//获得文件路径
RandomAccessFile raf=new RandomAccessFile(file,"rw");//RandomAccessFile是向指定文件中添加内容,FileOutputStream是直接覆盖原有文件内容
raf.seek(file.length());//将文件记录指针移到文件最后
raf.write(str.getBytes());//输出文件内容
raf.close();//关闭IO流
} catch (Exception e) {
e.printStackTrace();
}
}
}
public void read(){
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
File sdCardDir=Environment.getDataDirectory();
BufferedReader buf;
try {
File file=new File(sdCardDir.getCanonicalPath()+fileName);
FileInputStream fis=new FileInputStream(file);
buf=new BufferedReader(new InputStreamReader(fis));
StringBuffer strbuf=new StringBuffer();
String line=null;
while((line=buf.readLine())!=null){//循环读取所有字符
strbuf.append(line);
}
buf.close();
test08.setText(strbuf.toString());
} catch (Exception e) {
}
}else{
}
}
}