用到的类 Environment 该类在android.os包中
保存代码如下:
/**
* 保存文件到sd卡
* @param fileName 文件名
* @param content 文件内容
* @throws Exception
*/
public void saveSd(String fileName,String content) throws Exception{
//Environment.getExternalStorageDirectory()获取存储卡的根目录,看方法名知其意
File file = new File(Environment.getExternalStorageDirectory(),fileName);
/*if(!file.exists()){
file.createNewFile();
}*/
FileOutputStream out = new FileOutputStream(file);
out.write(content.getBytes());
out.close();
}
使用的时候要先判断内存卡是否存在:
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
fileService.saveSd(file, content);
Toast.makeText(getApplicationContext(), R.string.success, 1).show();
} else {
Toast.makeText(getApplicationContext(), R.string.sderror, 1).show();
}
权限:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />