作者微信 bishe2022

代码功能演示视频在页面下方,请先观看;如需定制开发,联系页面右侧客服
Android学习笔记之文件的保存与读取

Custom Tab

开发环境:

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

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

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

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

ffff.jpg

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

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

<?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文件中实现上述布局,代码如下:

<?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.为“保存”按钮添加点击处理事件

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

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

在MainActivity类中添加ButtonOnClickListener类:

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();
        }
   }     
}

上面代码中的

service.save(filename,content);

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

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测试文件的读取方法,代码如下:

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);
    }
}

将应用部署到模拟器上,运行的结果如下:

gggg.jpg

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

hhhhhhhhhhhhhhhhhhhhhhh.png

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

jjjjjjjjjjjjjjjj.png

转载自:http://blog.51cto.com/020618/1293664


Home