Android实现文件的保存与读取功能示例


本文实例讲述了Android实现文件的保存与读取功能。分享给大家供大家参考,具体如下:

注: 在Activity中有 getFileDir() 和 getCacheDir(); 方法可以获得当前的手机自带的存储空间中的当前包文件的路径

getFileDir() ----- /data/data/cn.xxx.xxx(当前包)/files
getCacheDir() ----- /data/data/cn.xxx.xxx(当前包)/cache

1. 编写文件读取与写入功能实现类 FileService

package cn.android.service;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import android.content.Context;
import android.util.Log;
/**
* 文件保存与读取功能实现类
* @author Administrator
*
* 2010-6-28 下午08:15:18
*/
public class FileService {
  public static final String TAG = "FileService";
  private Context context;
  //得到传入的上下文对象的引用
  public FileService(Context context) {
   this.context = context;
  }
  /**
   * 保存文件
   *
   * @param fileName 文件名
   * @param content 文件内容
   * @throws Exception
   */
  public void save(String fileName, String content) throws Exception {
   // 由于页面输入的都是文本信息,所以当文件名不是以.txt后缀名结尾时,自动加上.txt后缀
   if (!fileName.endsWith(".txt")) {
    fileName = fileName + ".txt";
   }
   byte[] buf = fileName.getBytes("iso8859-1");
   Log.e(TAG, new String(buf,"utf-8"));
   fileName = new String(buf,"utf-8");
   Log.e(TAG, fileName);
   // Context.MODE_PRIVATE:为默认操作模式,代表该文件是私有数据,只能被应用本身访问,在该模式下,写入的内容会覆盖原文件的内容,如果想把新写入的内容追加到原文件中。可以使用Context.MODE_APPEND
   // Context.MODE_APPEND:模式会检查文件是否存在,存在就往文件追加内容,否则就创建新文件。
   // Context.MODE_WORLD_READABLE和Context.MODE_WORLD_WRITEABLE用来控制其他应用是否有权限读写该文件。
   // MODE_WORLD_READABLE:表示当前文件可以被其他应用读取;MODE_WORLD_WRITEABLE:表示当前文件可以被其他应用写入。
   // 如果希望文件被其他应用读和写,可以传入:
   // openFileOutput("output.txt", Context.MODE_WORLD_READABLE + Context.MODE_WORLD_WRITEABLE);
   FileOutputStream fos = context.openFileOutput(fileName, context.MODE_PRIVATE);
   fos.write(content.getBytes());
   fos.close();
  }
  /**
   * 读取文件内容
   *
   * @param fileName 文件名
   * @return 文件内容
   * @throws Exception
   */
  public String read(String fileName) throws Exception {
   // 由于页面输入的都是文本信息,所以当文件名不是以.txt后缀名结尾时,自动加上.txt后缀
   if (!fileName.endsWith(".txt")) {
    fileName = fileName + ".txt";
   }
   FileInputStream fis = context.openFileInput(fileName);
   ByteArrayOutputStream baos = new ByteArrayOutputStream();
   byte[] buf = new byte[1024];
   int len = 0;
   //将读取后的数据放置在内存中---ByteArrayOutputStream
   while ((len = fis.read(buf)) != -1) {
    baos.write(buf, 0, len);
   }
   fis.close();
   baos.close();
   //返回内存中存储的数据
   return baos.toString();
  }
}

2. 编写Activity类:

package cn.android.test;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import cn.android.service.FileService;
public class TestAndroidActivity extends Activity {
  /** Called when the activity is first created. */
  //得到FileService对象
  private FileService fileService = new FileService(this);
  //定义视图中的filename输入框对象
  private EditText fileNameText;
  //定义视图中的contentText输入框对象
  private EditText contentText;
  //定义一个土司提示对象
  private Toast toast;
  @Override
  public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);
  //得到视图中的两个输入框和两个按钮的对象引用
  Button button = (Button)this.findViewById(R.id.button);
  Button read = (Button)this.findViewById(R.id.read);
  fileNameText = (EditText) this.findViewById(R.id.filename);
  contentText = (EditText) this.findViewById(R.id.content);
  //为保存按钮添加保存事件
  button.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
     String fileName = fileNameText.getText().toString();
     String content = contentText.getText().toString();
     //当文件名为空的时候,提示用户文件名为空,并记录日志。
     if(isEmpty(fileName)) {
      toast = Toast.makeText(TestAndroidActivity.this, R.string.empty_filename, Toast.LENGTH_LONG);
      toast.setMargin(RESULT_CANCELED, 0.345f);
      toast.show();
      Log.w(fileService.TAG, "The file name is empty");
      return;
     }
     //当文件内容为空的时候,提示用户文件内容为空,并记录日志。
     if(isEmpty(content)) {
      toast = Toast.makeText(TestAndroidActivity.this, R.string.empty_content, Toast.LENGTH_LONG);
      toast.setMargin(RESULT_CANCELED, 0.345f);
      toast.show();
      Log.w(fileService.TAG, "The file content is empty");
      return;
     }
     //当文件名和内容都不为空的时候,调用fileService的save方法
     //当成功执行的时候,提示用户保存成功,并记录日志
     //当出现异常的时候,提示用户保存失败,并记录日志
     try {
      fileService.save(fileName, content);
      toast = Toast.makeText(TestAndroidActivity.this, R.string.success, Toast.LENGTH_LONG);
      toast.setMargin(RESULT_CANCELED, 0.345f);
      toast.show();
      Log.i(fileService.TAG, "The file save successful");
     } catch (Exception e) {
      toast = Toast.makeText(TestAndroidActivity.this, R.string.fail, Toast.LENGTH_LONG);
      toast.setMargin(RESULT_CANCELED, 0.345f);
      toast.show();
      Log.e(fileService.TAG, "The file save failed");
     }
    }
  });
  //为读取按钮添加读取事件
  read.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
     //得到文件名输入框中的值
     String fileName = fileNameText.getText().toString();
     //如果文件名为空,则提示用户输入文件名,并记录日志
     if(isEmpty(fileName)) {
      toast = Toast.makeText(TestAndroidActivity.this, R.string.empty_filename, Toast.LENGTH_LONG);
      toast.setMargin(RESULT_CANCELED, 0.345f);
      toast.show();
      Log.w(fileService.TAG, "The file name is empty");
      return;
     }
     //调用fileService的read方法,并将读取出来的内容放入到文本内容输入框里面
     //如果成功执行,提示用户读取成功,并记录日志。
     //如果出现异常信息(例:文件不存在),提示用户读取失败,并记录日志。
     try {
      contentText.setText(fileService.read(fileName));
      toast = Toast.makeText(TestAndroidActivity.this, R.string.read_success, Toast.LENGTH_LONG);
      toast.setMargin(RESULT_CANCELED, 0.345f);
      toast.show();
      Log.i(fileService.TAG, "The file read successful");
     } catch (Exception e) {
      toast = Toast.makeText(TestAndroidActivity.this, R.string.read_fail, Toast.LENGTH_LONG);
      toast.setMargin(RESULT_CANCELED, 0.345f);
      toast.show();
      Log.e(fileService.TAG, "The file read failed");
     }
    }
  });
  }
  //编写一个isEmpty方法,判断字符串是否为空
  private boolean isEmpty(String s) {
  if(s == null || "".equals(s.trim())) {
   return true;
  }
  return false;
  }
}

3.文件布局文件: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/content"
  />
  <EditText
   android:layout_width="fill_parent"
   android:layout_height="wrap_content"
   android:minLines="3"
   android:id="@+id/content"
  />
  <LinearLayout
  android:orientation="horizontal"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent">
   <Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/button"
    android:text="@string/save"
   />
   <Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/read"
    android:text="@string/read"
   />
  </LinearLayout>
</LinearLayout>

PS:由于我在测试这个功能的时候发现文件名无法使用中文(sdk2.2 + 模拟器),如果有哪为高手无意中浏览此文章后,能对这个问题予以指点,我将感激不尽。呵呵。

更多关于Android相关内容感兴趣的读者可查看本站专题:《Android文件操作技巧汇总》、《Android编程之activity操作技巧总结》、《Android视图View技巧总结》、《Android操作SQLite数据库技巧总结》、《Android操作json格式数据技巧总结》、《Android数据库操作技巧总结》、《Android编程开发之SD卡操作方法汇总》、《Android开发入门与进阶教程》、《Android资源操作技巧汇总》及《Android控件用法总结》

希望本文所述对大家Android程序设计有所帮助。


« 
» 
快速导航

Copyright © 2016 phpStudy | 豫ICP备2021030365号-3