【Android进阶】如何使用文件来保存程序中的数据
来源:互联网 发布:吾知所以距子矣的距 编辑:程序博客网 时间:2024/05/01 14:35
在程序中,有很多保存和获取数据的方法,本篇文章,主要介绍使用文件系统对程序中的数据进行保存和读取的操作
我直接写了一个帮助类,进行文件的写入和读取操作
- /**
- * 用于在文件中保存程序数据
- *
- * @author zhaokaiqiang
- *
- */
- public class FileHelper {
- private static final String TAG = "FileHelper";
- private Context mContext;
- FileHelper(Context _mContext) {
- mContext = _mContext;
- }
- // 在手机本地硬盘中保存信息
- public void save(String fileName, String content) {
- FileOutputStream fileOutputStream = null;
- try {
- fileOutputStream = mContext.openFileOutput(fileName,
- Context.MODE_PRIVATE);
- fileOutputStream.write(content.getBytes());
- } catch (FileNotFoundException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- } finally {
- try {
- if (fileOutputStream != null) {
- fileOutputStream.close();
- }
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- // 读取手机硬盘中保存的文件
- public void read(String fileName) {
- FileInputStream fileInputStream = null;
- try {
- fileInputStream = mContext.openFileInput(fileName);
- int len = 0;
- byte[] buffer = new byte[1024];
- ByteArrayOutputStream byteArrayInputStream = new ByteArrayOutputStream();
- while ((len = fileInputStream.read(buffer)) != -1) {
- byteArrayInputStream.write(buffer, 0, len);
- }
- String string = new String(byteArrayInputStream.toByteArray());
- Log.d(TAG, string);
- } catch (FileNotFoundException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- } finally {
- if (fileInputStream != null) {
- try {
- fileInputStream.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- }
- }
注意:使用写入操作的时候,写入的内容会将上次写入的内容进行覆盖
写入的文件保存在/data/data/package name/files目录下,使用DDMS可以进行查看
如下图所示:
使用DDMS将文件导出,即可查看内容
0 0
- 【Android进阶】如何使用文件来保存程序中的数据
- 【Android进阶】如何使用文件来保存程序中的数据
- 如何使用文件来保存程序中的数据
- 如何使用文件来保存程序中的数据
- 使用文件来保存程序中的数据
- c++使用vector来保存程序数据
- 使用SharedPreferences来保存数据
- 在android中使用java 的preferences来保存数据
- android中的数据保存
- android 文件保存数据
- 如何把文件中的数据读入程序
- android工程中把数据保存到文件中的class
- python中的文件数据保存
- 『Python思考』利用字典来保存程序中的文件地址(路径名)
- Android下使用Properties文件保存程序设置
- Android下使用Properties文件保存程序设置
- Android下使用Properties文件保存程序设置
- Android下使用Properties文件保存程序设置
- 雁儿,你飞慢些吧
- 李克强批“为官不为”:说得难听点 不就是尸位素餐吗
- Codeforces Round #250 Div. 2(C.The Child and Toy)
- 珍爱,你懂的
- Android TextView内容过长加省略号,点击显示全部内容
- 【Android进阶】如何使用文件来保存程序中的数据
- google推出的SwipeRefreshLayout下拉刷新用法
- 简单版QQ聊天
- 环境变量
- android数据对外共享的方式----contentProvider
- 电感磁芯公式
- OpenCV2马拉松第25圈——直线拟合与RANSAC算法
- mysql 启动错误集锦
- 情殇