当前位置: 移动技术网 > IT编程>移动开发>Android > Android实现文件的保存与读取功能示例

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

2019年07月24日  | 移动技术网IT编程  | 我要评论

彩票1604488,蔡承颖,非常可乐官网

本文实例讲述了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程序设计有所帮助。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网