【数据存储】利用IO流操作文件
package org.lxh.demo; import java.io.File; import java.io.FileOutputStream; import java.io.PrintStream; import android.app.Activity; import android.os.Bundle; public class FileOperate extends Activity { // 设置文件名称 private static final String FILENAME = "/mnt/sdcard/mldndata/mymldn.txt" ; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); super.setContentView(R.layout.main); // 定义要操作的文件 File file = new File(FILENAME) ; // 文件不存在 if(!file.getParentFile().exists()) { // 创建文件夹路径 file.getParentFile().mkdirs() ; } // 打印流对象用于输出 PrintStream out = null; try { out = new PrintStream(new FileOutputStream(file)); out.println("噜啦啦啦啦啦啦啦"); } catch (Exception e) { e.printStackTrace() ; } finally { // 一定要关闭流 if(out != null) { out.close() ; } } } } <!-- 运行操作sdcard的权限 --> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
从sdcard读取文件
File file2 = new File(FILENAME); if (!file2.getParentFile().exists()) { file2.getParentFile().mkdirs(); } Scanner scann = null; try { scann = new Scanner(new FileInputStream(file2)); while (scann.hasNext()) { this.tv_msg.append(scann.next() + "\n"); } } catch (Exception e) { // TODO: handle exception } finally { if (scann != null) { scann.close(); } }