Android学习笔记之文件的保存与读取









































































































开发环境:

Win XP + eclipse-jee-helios(版本号3.6) + ADT(版本10.0.1) + Android SDK(版本10);

模拟器及真机测试环境:Android2.2


   在很多的应用中,需要对数据进行存储,以供再次的访问,Android为数据的存储提供了以下5中方式:

  • 文件(使用的是Java中的IO技术)

  • SharedPreferences(参数)

  • SQLite数据库

  • Content provider(内容提供者)

  • 网络


首先看一下文件数据存储方式

   1.应用的界面布局如下,当用户点击“保存”按钮,应当可以以文件的形式保存用户输入的内容。

说明:文件可以保存在手机的两个位置,一个是手机自带的存储空间(一般这个容量比较小),另外一个是外存储设备(SDCard,一般容量比较大)。

   2.在项目File->res->values目录下的string.xml文件中,定义布局中使用的字符串,代码如下:

1
2
3
4
5
6
7
8
9
10
<? xml  version = "1.0"  encoding = "utf-8" ?>
< resources >
     < string  name = "hello" >Hello World, MainActivity!</ string >
     < string  name = "app_name" >文件操作</ string >
     < string  name = "filename" >文件名称</ string >
     < string  name = "filecontent" >文件内容</ string >
     < string  name = "button" >保存</ string >
     < string  name = "success" >保存完成</ string >
     < string  name = "fail" >保存失败</ string >
</ resources >

   3.在项目File->res->layout目录下的main.xml文件中实现上述布局,代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
<? xml  version = "1.0"  encoding = "utf-8" ?>
< LinearLayout  xmlns:android = "http://schemas.android.com/apk/res/android"
     android:orientation = "vertical"
     android:layout_width = "fill_parent"
     android:layout_height = "fill_parent"
     >
     < TextView
         android:layout_width = "fill_parent"
         android:layout_height = "wrap_content"
         android:text = "@string/filename"
     />
      < EditText
         android:layout_width = "fill_parent"
         android:layout_height = "wrap_content"
         android:id = "@+id/filename"
      />
      < TextView
         android:layout_width = "fill_parent"
         android:layout_height = "wrap_content"
         android:text = "@string/filecontent"
       />
      < EditText
         android:layout_width = "fill_parent"
         android:layout_height = "wrap_content"
         android:minLines = "3"
         android:id = "@+id/filecontent"
      />
      < Button
         android:layout_width = "wrap_content"
         android:layout_height = "wrap_content"
         android:text = "@string/button"
         android:id = "@+id/button"
      />
</ LinearLayout >

   4.为“保存”按钮添加点击处理事件

   思路:找到按钮,监听点击事件,添加点击事件处理对象。

  • 在MainActivity类的onCreate()方法中添加如下代码:

1
2
Button button = (Button) this .findViewById(R.id.button);
button.setOnClickListener( new  ButtonOnClickListener());

在MainActivity类中添加ButtonOnClickListener类:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
private  final  class  ButtonOnClickListener  implements  View.OnClickListener{
        @Override
      public  void  onClick(View v) {
          EditText filenameText = (EditText)findViewById(R.id.filename);
          EditText contentText = (EditText)findViewById(R.id.filecontent);
          String filename = filenameText.getText().toString();
          String content = contentText.getText().toString();
          FileService service =  new  FileService(getApplicationContext()); //参数是取得上下文对象
          try  {
             service.save(filename,content);
             Toast.makeText(getApplication(),R.string.success,  1 ).show();
          catch  (Exception e) {
             Toast.makeText(getApplication(), R.string.fail,  1 ).show();
             e.printStackTrace();
         }
    }     
}
  • 上面代码中的

1
service.save(filename,content);

是文件的保存的方法,在cn.hao.service包中创建FileService类,在该类中实现文件的保存读取方法,代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
public  class  FileService {
     private  Context context; //Android提供的上下文对象
//通过构造器给context赋值
     public  FileService(Context context) {
     super ();
     this .context = context;
     }
                                                                                                                               
     /**
     * 保存文件
     * @param filename 文件名称
     * @param content 文件内容
     */
     public  void  save( String  filename,  String  content) throws Exception{
//java中的IO技术来保存文件
//得到文件的输出流对象
     FileOutputStream outStream = context.openFileOutput(filename, Context.MODE_PRIVATE); //filename不可以带路径
//mode往文件写的模式:追加、覆盖、针对不同的组的操作权限
//Context.MODE_PRIVATE私有操作模式,创建出来的文件只能为本应//用使用;采用私有模式创建的文件
//写入文件中的内容会覆盖原文件内容,默认会保
//存在data/data/应用包下/files目录下
//将输出流写入文件
     outStream.write(content.getBytes());
//写完文件之后要关闭流
     outStream.close();
     }
     /**
     * 读取文件内容
     * @param filename 文件名称
     * @return   文件内容
     * @throws Exception
     */
     public  String  read( String  filename) throws Exception{
//方法openFileInput(filename)会默认从data/当前应
//用包下/files目录下读取
     FileInputStream inStream = context.openFileInput(filename);
//从内存输出的数据流对象
     ByteArrayOutputStream outStream =  new  ByteArrayOutputStream();
//从文件中读取数据,先把输入流中的数据读取到一个字节数组中,//输入流中的数据可能很多,应该利用循环实现
     byte[] buffer =  new  byte[ 1024 ]; //定义一个字节数组
     int  len =  0 ;
//若未达到文件尾,就一直读
     while ((len = inStream.read(buffer)) != - 1 ){
     //得到每次读取到的数据
     outStream.write(buffer,  0 , len);
     }
     byte[] data = outStream.toByteArray();
//data和上面方法content.getBytes()的数据是一致的
     return  new  String (data);
     }
}
  • 引入测试,这时需要创建的类需要继承AndroidTestCase,并在AndroidManifest.xml文件中引入测试类库,这个在前面的文章以提到,在package cn.hao.Test下新建测试类FileServiceTest测试文件的读取方法,代码如下:

1
2
3
4
5
6
7
8
9
10
11
public  class  FileServiceTest  extends  AndroidTestCase {
//为日志定义一个标记
     private  static  final  String TAG =  "FileServiceTest" ;
     public  void  testRead()  throws  Throwable{
         FileService service =  new  FileService( this .getContext());
//this.getContext()取得当前应用的上下文对象this.getContext()
//文件名称应该包含后缀名
         String result = service.read( "Hello.txt" );
         Log.i(TAG, result);
     }
}
  • 将应用部署到模拟器上,运行的结果如下:

  • 当点击保存时候就可以在data/data/files目录下看到该文件,导出到桌面,可以看到文件的内容就是输入的内容,效果如下:

  • 运行测试方法testRead(),新建一个日志过滤器,就可以看到读取到的文件的内容:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值