1.界面设计
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<EditText
android:id="@+id/zh"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="账号"/>
<EditText
android:id="@+id/mm"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="密码" />
<Button
android:id="@+id/save"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="保存用户信息" />
<Button
android:id="@+id/show"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="读取用户信息" />
</LinearLayout>
2.编写 MainActivity 中的代码,实现保存和读取功能
上述界面设计完成以后,接下来就需要在 MainActivity 中初始化上述布局的组件,然后为按钮添加监听以实现用户信息的保存和读取。
public class MainActivity extends Activity implements View.OnClickListener {
public EditText username,paswd;
public Button save,show;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout);
init();
}
private void init() {
username =( EditText ) findViewById ( R . id .zh );
paswd =( EditText ) findViewById ( R . id .mm );
save =( Button ) findViewById ( R . id . save );
show=( Button ) findViewById ( R . id . show );
save.setOnClickListener ( this );
show.setOnClickListener ( this );
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.save:
String user_str = username.getText ().toString();
String paswd_str = paswd. getText ().toString();
String user_mes="用户名为:"+user_str+"\n"+"密码为:"+paswd_str;
FileOutputStream fi_out;
try{
//保存输入数据
fi_out=openFileOutput("user_mes.txt",MODE_PRIVATE);
fi_out.write(user_mes.getBytes());
fi_out.close();
}catch (Exception e){
e.printStackTrace();
}
Toast.makeText(this,"用户信息已保存",Toast.LENGTH_SHORT).show();
break;
case R.id.show:
String mes=" ";
try{
//存储读取的信息
FileInputStream fi_input;
fi_input=openFileInput("user_mes.txt");
byte[] buffer=new byte[fi_input.available()];
fi_input.read(buffer);
mes=new String(buffer);
fi_input.close();
}catch (Exception e){
e.printStackTrace();
}
Toast.makeText(this,mes,Toast.LENGTH_SHORT).show();
break;
default:
break;
}
}
}
上述代码把用户输入的账号和密码保存到 user _ mes . txt 文件,并且实现了从文件中读取并里显示的功能,重点在于对按钮监听事件的处理。
3.程序运行
完成了布局文件和 MainActivity 代码的编写以后,运行程序,单击“保存用户信息”按钮就会把用户信息保存到 user mes . txt 文件中,并且提示用户保存成功;单击“读取用户信息”按钮就会从 user mes . txt 文件中读取保存的信息,然后通过 Toast 的形式显示出来。
4.查看 user mes . txt 文件是否存在
为了确定上述代码是否产生了 user _ mes . txt 文件,可以在 data / data /目录下査找。