其实就是普通的文件操作,不过还是有些地方需要注意。比如:
1.加入sdcard操作权限;
2.确认sdcard的存在;
3.不能直接在非sdcard的根目录创建文件,而是需要先创建目录,再创建文件;
实例:
(1)在AndroidManifest.xml添加sdcard操作权限
1: <!-- sdcard权限 -->
2: <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
(2)变量声明:
1: private final static String PATH = "/sdcard/digu";2: private final static String FILENAME = "/notes.txt";(3)向sdcard写文件
1: /**2: * 写文件3: */4: private void onWrite() {5: try {6: Log.d(LOG_TAG, "Start Write");7: //1.判断是否存在sdcard8: if (Environment.MEDIA_MOUNTED.equals(Environment9: .getExternalStorageState())) {
10: //目录11: File path = new File(PATH);12: //文件13: File f = new File(PATH + FILENAME);14: if(!path.exists()){15: //2.创建目录,可以在应用启动的时候创建16: path.mkdirs();
17: }
18: if (!f.exists()) {19: //3.创建文件20: f.createNewFile();
21: }
22: OutputStreamWriter osw = new OutputStreamWriter(23: new FileOutputStream(f));24: //4.写文件,从EditView获得文本值25: osw.write(editor.getText().toString());
26: osw.close();
27: }
28: } catch (Exception e) {29: Log.d(LOG_TAG, "file create error");30: }
31: }
完毕,呵呵……
原文地址为:http://www.cnblogs.com/halzhang/archive/2010/05/28/1746590.html