当前位置: 移动技术网 > IT编程>移动开发>Android > Android基础教程数据存储之文件存储

Android基础教程数据存储之文件存储

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

纸袋印刷厂,a101不锈钢焊条,单城双恋

android基础教程数据存储之文件存储

将数据存储到文件中并读取数据

1、新建filepersistencetest项目,并修改activity_main.xml中的代码,如下:(只加入了edittext,用于输入文本内容,不管输入什么按下back键就丢失,我们要做的是数据被回收之前,将它存储在文件中)

<?xml version="1.0" encoding="utf-8"?>
<linearlayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:id="@+id/activity_main"
  android:layout_width="match_parent"
  android:layout_height="match_parent">

  <edittext
    android:id="@+id/edit"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:hint="type something here"/>
</linearlayout>

2、修改mainactivity中的代码,如下:(save()方法将一段文本内容保存到文件中,load()方法从文件中读取数据,套用)

public class mainactivity extends appcompatactivity {
  private edittext edit;

  @override
  protected void oncreate(bundle savedinstancestate) {
    super.oncreate(savedinstancestate);
    setcontentview(r.layout.activity_main);
    edit=(edittext) findviewbyid(r.id.edit);
    string inputtext=load();
    if(!textutils.isempty(inputtext)){                 //对字符串进行非空判断
      edit.settext(inputtext);
      edit.setselection(inputtext.length());
      toast.maketext(this,"restoring succeeded",toast.length_short).show();
    }

  }
  @override
  protected void ondestroy(){                      //重写ondestroy()保证在活动销毁之前一定调用这个方法
    super.ondestroy();
    string inputtext=edit.gettext().tostring();
    save(inputtext);
  }

  public void save(string inputtext){
    fileoutputstream out=null;
    bufferedwriter writer=null;
    try{
      out=openfileoutput("data", context.mode_private);
      writer=new bufferedwriter(new outputstreamwriter(out));
      writer.write(inputtext);
    }catch(ioexception e){
      e.printstacktrace();
    }finally{
      try{
        if(writer!=null){
          writer.close();
        }
      }catch(ioexception e){
        e.printstacktrace();
      }
    }
  }

  public string load(){
    fileinputstream in=null;
    bufferedreader reader=null;
    stringbuilder content=new stringbuilder();
    try{
      in=openfileinput("data");
      reader=new bufferedreader(new inputstreamreader(in));
      string line="";
      while((line=reader.readline())!=null){
        content.append(line);
      }
    }catch(ioexception e){
      e.printstacktrace();
    }finally {
      if(reader!=null){
        try{
          reader.close();
        }catch (ioexception e){
          e.printstacktrace();
        }
      }
    }
    return content.tostring();
  }
}

运行程序,效果如下:(输入content后按back键返回,重新打开)

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

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

相关文章:

验证码:
移动技术网