Android 存储数据之1 读取文件和存储文件

      Android文件存储的方式并不适合用于保存一些较为复杂的文本数据.

TextUtils.isEmpty(inputText),非常好用,它可以一次性判断两种空值.当传入的字符串等于null或者等于空字符串
 * 的时候,这个方法都会返回true,从而使得我们不需要单独去判断着两种空值,再使用逻辑运算符连接起来了.


其实用到的核心技术就是Context类中提供的openFileInput()和openFileOutput()方法


存储文件

public void save(String data) {
		FileOutputStream out = null; // 文件输出流,输出内容到文件中
		BufferedWriter writer = null; // 缓冲流
		try {
			// 打开文件,如果不存在,则创建.如果存在,则覆盖原来的内容
			out = openFileOutput("data", Context.MODE_PRIVATE);

			// out = openFileOutput("data", Context.MODE_APPEND); //
			// 打开文件,添加内容到文件末尾

			// OutputStreamWriter是转换流
			/*
			 * OutputStreamWriter 是字符流通向字节流的桥梁:可使用指定的 charset 将要写入流中的字符编码成字节。
			 * 它使用的字符集可以由名称指定或显式给定,否则将接受平台默认的字符集。
			 * 
			 * 为了获得最高效率,可考虑将 OutputStreamWriter 包装到 BufferedWriter
			 * 中,以避免频繁调用转换器。例如:
			 * 
			 * Writer out = new BufferedWriter(new
			 * OutputStreamWriter(System.out));
			 */
			writer = new BufferedWriter(new OutputStreamWriter(out));
			writer.write(data); // 向文件中写入数据
			Toast.makeText(MainActivity.this, "保存成功!", 0).show();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (writer != null) { // 需要在finally中关闭文件流,关闭之前判断是否为空
				try {
					writer.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}


读取文件

public String readFile() {
FileInputStream input = null;
BufferedReader reader = null;
try {
// 打开文件,有可能文件找不到,抛出FileNotFoundException异常
input = openFileInput("data");
if (input != null) {
//BufferedReader
// 这个类就是一个包装类,它可以包装字符流,将字符流放入缓存里,先把字符读到缓存里,
// 到缓存满了或者你flush的时候,再读入内存,就是为了提供读的效率而设计的
reader = new BufferedReader(new InputStreamReader(input));
String line = "";
while ((line = reader.readLine()) != null) { // 一行一行的读取
data_file.append(line + "\n");
}
Toast.makeText(MainActivity.this, "读取文件成功", 0).show();
// edit.setText(data_file); //设置数据到EditText控件中
// Log.i("xfhy","文件内容:"+data_file);
return data_file.toString();
}
} catch (FileNotFoundException e1) { // 文件不存在
Toast.makeText(MainActivity.this, "文件不存在", 0).show();
e1.printStackTrace();
} catch (Exception e2) {
e2.printStackTrace();
} finally {
if (input != null) { // 关闭输入流
try {
input.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
return null;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值