在AndroidManifest.xml中加入访问SDCard的权限如下:
<!-- 在SDCard中创建与删除文件权限 -->
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
<!-- 往SDCard写入数据权限 -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Environment.getExternalStorageState()方法用于获取SDCard的状态,如果手机装有SDCard,并且可以进行读写,那么方法返回的状态等于Environment.MEDIA_MOUNTED。
Environment.getExternalStorageDirectory()方法用于获取SDCard的目录
Service层中的保存方法:
public class FileService {
private Context context;
public FileService(Context context){
this.context = context;
}
/**
* 保存到SD卡中
*/
public void saveToSDCard(String filename, String filecontent) throws Exception{
//Environment.getExternalStorageDirectory()获得SD卡路径即外存主设备的目录
File file = new File(Environment.getExternalStorageDirectory(),filename);
FileOutputStream outputStream=new FileOutputStream(file);
outputStream.write(filecontent.getBytes());
outputStream.close();
}
判断sd卡,并保存:
public class FileActivity extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button button = (Button) this.findViewById(R.id.button);
button.setOnClickListener(new ButtonClickListener());
}
public final class ButtonClickListener implements View.OnClickListener{
public void onClick(View v) {
//找到文件名称位置
EditText filenameText = (EditText) findViewById(R.id.filename);
//找到文件内容位置
EditText filecontentText = (EditText) findViewById(R.id.filecontent);
//得到文件名称
String filename = filenameText.getText().toString();
//得到文件内容
String filecontent = filecontentText.getText().toString();
//获取一个业务层对象
FileService service = new FileService(getApplicationContext());
try {
//判断SDCard是否存在并可读写
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
service.saveToSDCard(filename,filecontent);
Toast.makeText(getApplicationContext(), R.string.success, 1).show();
}else{
Toast.makeText(getApplicationContext(), R.string.sdcarderr, 1).show();
}
} catch (Exception e) {
Toast.makeText(getApplicationContext(), R.string.failed, 1).show();
e.printStackTrace();
}
}
}
}
保存后xxx.txt放在/mnt/sdcard