【Android进阶】如何使用文件来保存程序中的数据

来源:互联网 发布:吾知所以距子矣的距 编辑:程序博客网 时间:2024/05/01 14:35

在程序中,有很多保存和获取数据的方法,本篇文章,主要介绍使用文件系统对程序中的数据进行保存和读取的操作


我直接写了一个帮助类,进行文件的写入和读取操作


[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. /** 
  2.  * 用于在文件中保存程序数据 
  3.  *  
  4.  * @author zhaokaiqiang 
  5.  *  
  6.  */  
  7. public class FileHelper {  
  8.   
  9.     private static final String TAG = "FileHelper";  
  10.     private Context mContext;  
  11.   
  12.     FileHelper(Context _mContext) {  
  13.         mContext = _mContext;  
  14.     }  
  15.   
  16.     // 在手机本地硬盘中保存信息  
  17.     public void save(String fileName, String content) {  
  18.   
  19.         FileOutputStream fileOutputStream = null;  
  20.         try {  
  21.             fileOutputStream = mContext.openFileOutput(fileName,  
  22.                     Context.MODE_PRIVATE);  
  23.             fileOutputStream.write(content.getBytes());  
  24.   
  25.         } catch (FileNotFoundException e) {  
  26.             e.printStackTrace();  
  27.         } catch (IOException e) {  
  28.             e.printStackTrace();  
  29.         } finally {  
  30.             try {  
  31.   
  32.                 if (fileOutputStream != null) {  
  33.                     fileOutputStream.close();  
  34.                 }  
  35.             } catch (IOException e) {  
  36.                 e.printStackTrace();  
  37.             }  
  38.         }  
  39.     }  
  40.   
  41.     // 读取手机硬盘中保存的文件  
  42.     public void read(String fileName) {  
  43.         FileInputStream fileInputStream = null;  
  44.         try {  
  45.             fileInputStream = mContext.openFileInput(fileName);  
  46.             int len = 0;  
  47.             byte[] buffer = new byte[1024];  
  48.             ByteArrayOutputStream byteArrayInputStream = new ByteArrayOutputStream();  
  49.             while ((len = fileInputStream.read(buffer)) != -1) {  
  50.                 byteArrayInputStream.write(buffer, 0, len);  
  51.             }  
  52.             String string = new String(byteArrayInputStream.toByteArray());  
  53.             Log.d(TAG, string);  
  54.         } catch (FileNotFoundException e) {  
  55.             e.printStackTrace();  
  56.         } catch (IOException e) {  
  57.             e.printStackTrace();  
  58.         } finally {  
  59.             if (fileInputStream != null) {  
  60.                 try {  
  61.                     fileInputStream.close();  
  62.                 } catch (IOException e) {  
  63.                     e.printStackTrace();  
  64.                 }  
  65.             }  
  66.         }  
  67.   
  68.     }  
  69. }  

注意:使用写入操作的时候,写入的内容会将上次写入的内容进行覆盖


写入的文件保存在/data/data/package name/files目录下,使用DDMS可以进行查看

如下图所示:


使用DDMS将文件导出,即可查看内容

0 0