Android 文件操作操作时,要赋予相应的权限:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
下面是向文件写文本的代码:
private final static String PATH = "/sdcard/lin"; private final static String FILENAME = "/test.txt"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); writeFile(); } private void writeFile() { //判断设备是否存在sdcard if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) { try { Log.d("File Operation", "start!"); File path = new File(PATH); File file = new File(PATH+FILENAME); //如果不存在此路径,则创建此路径 if (!path.exists()) { path.mkdir(); } //如果不存在此文件,则创建此文件 if (!file.exists()) { file.createNewFile(); } //将"text message!"信息写入相应的文件 OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(file)); osw.write("text message!"); osw.close(); Log.d("File Operation", "success!"); } catch (Exception e) { Log.d("File Operation", "file create error"); } } }