进行对SD卡的资料获取和写入操作
1.检测外置SD卡的状态
String state=
Environment.getExternalStorageState()
Log.i("TAG", "state="+state)
if(!state.equals(Environment.MEDIA_MOUNTED)||
Environment.isExternalStorageRemovable()){
Toast.makeText(this, "请确保SDCARD可用", 0).show()
return
}
2.获得外置sdcard的公有存储目录
//2.1获得外部存储的根目录
File sdcard=//mnt/sdcard
Environment.getExternalStorageDirectory();
Log.i("TAG", "sdcard="+sdcard.getPath());
//2.2获得外部存储的子目录
File picDir=//mnt/sdcard/Pictures
Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES);
Log.i("TAG", "picDir="+picDir.getPath());
2.获得外置sdcard的私有存储目录(此目录的获得需要添加写权限)
File sdcardText=getExternalFilesDir("mydir");
StatFs sf=new StatFs(sdcardText.getPath());
String text="helloworld";
if(text.getBytes().length>
sf.getAvailableBlocks()*sf.getBlockSize()){
Toast.makeText(this, "磁盘空间不足", 0).show();
return;
}
3.获得外置sdcard的可用空间大小
StatFs sf=new StatFs(sdcard.getPath())
//sf.getBlockCount() 块的总数量
//sf.getFreeBlocks() 空闲块数>=可用块
//sf.getAvailableBlocks() 可用块数
//sf.getBlockSize()
double totalSize=//M
sf.getBlockCount()*sf.getBlockSize()*1.0/1024/1024
Log.i("TAG", "totalSize="+totalSize)
String text="helloworld"
if(text.getBytes().length>
sf.getAvailableBlocks()*sf.getBlockSize()){
Toast.makeText(this, "磁盘空间不足", 0).show()
return
}
直接IO写入数据
OutputStream out=null;
try{
out=new FileOutputStream(new File(sdcardText,"d1.txt"));
out.write(text.getBytes());
Log.i("TAG", "write ok!");
}catch(Exception e){
e.printStackTrace();
}finally{
if(out!=null)try{out.close();}catch(Exception e){}
}
获取私有数据目录需要添加如下权限到清单配置文件
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>