转载自:http://blog.csdn.net/csdn_lzj_2008/article/details/55002165
文件写入SD卡与写入手机内存其实是一样。
区别就是存在SD卡的文件,没有权限这一回事。就是存在SD卡上文件没有所谓的“读写权限”,只要写在SD卡都是可以被其他应用访问的。
但是有一点就是程序访问SD卡的时候,是需要权限的。读写到SD也是需要权限。
权限设置如下
在CODE上查看代码片派生到我的代码片
<uses-permission android:name="android.permission.MOUNT_FORMAT_FILESYSTEMS"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
具体的操作
在CODE上查看代码片派生到我的代码片
String name=fileName.getText().toString();
String content=fileContent.getText().toString();
FileService file=new FileService(getApplicationContext());
try {
//获取SD的存储状态(有些SD有读写保护)
//Environment.MEDIA_MOUNTED 可以进行读写
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
file.SaveToSD(name,content);
Toast.makeText(MainActivity.this, "文件保存成功", 1).show();
}else{
Toast.makeText(MainActivity.this, "SD卡不存在", 1).show();
}
} catch (Exception e) {
// TODO Auto-generated catch block
Toast.makeText(MainActivity.this, "文件保存失败", 1).show();
e.printStackTrace();
}
FileService
[java] view plain copy
在CODE上查看代码片派生到我的代码片
/**
* 文件保存在SD卡上
* @param name 文件名称
* @param content 文件内容
* @throws Exception
*/
public void SaveToSD(String name, String content)throws Exception{
//获取外部设备
//Environment.getExternalStorageDirectory() 获取SD的路径
File file=new File(Environment.getExternalStorageDirectory(),name);
FileOutputStream outStream=new FileOutputStream(file);
//写入文件
outStream.write(content.getBytes());
outStream.close();
}