代码演示是登陆界面的记住账号与密码的功能实现,当勾选记住账号与密码后,将其存储到文件中
内部存储:
//写操作
public void write(View v) {
EditText et_name = (EditText) findViewById(R.id.et_name);
EditText et_pass = (EditText) findViewById(R.id.et_pass);
String name = et_name.getText().toString();
String pass = et_pass.getText().toString();
CheckBox cb = (CheckBox) findViewById(R.id.cb);
// 判断选框是否勾选
if (cb.isChecked()) {
// 引号内容是文件地址,内部存储空间
File file = new File("data/data/your.lc.file/info.txt");
// 使用API调用文件地址
// File file = new File(getFilesDir(),"info.txt");
// 另外一种使用API调用地址,缓存文件夹,意思是里面的内容会被系统自动删除
//应用:比如浏览的照片,头像等不需要长久保存的信息
// File file = new File(getCacheDir(),"info.txt");
try {
FileOutputStream fos = new FileOutputStream(file);
//将数据存储进去,并以##作为分隔符,方便读操作
fos.write((name + "##" + pass).getBytes());
fos.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
}
}
//对登陆校验操作没有进行,只是简单的输出一个对话框
Toast.makeText(this, "登陆成功", Toast.LENGTH_SHORT).show();
;
}
读操作:
public void read() {
File file = new File("data/data/your.lc.file/info.txt");
// 使用API调用文件地址
// File file = new File(getFilesDir(),"info.txt");
//首先判断文件是否存在
if (file.exists()) {
try {
FileInputStream fis = new FileInputStream(file);
// 将字节流转换为字符流
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
// 读取TXT文件里的用户名和密码
String text = br.readLine();
// 根据关键字分割存储数据
String[] s = text.split("##");
EditText et_name = (EditText) findViewById(R.id.et_name);
EditText et_pass = (EditText) findViewById(R.id.et_pass);
et_name.setText(s[0]);
et_pass.setText(s[1]);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
外部存储就是存储到SD卡中
public void write(View v) {
EditText et_name = (EditText) findViewById(R.id.et_name);
EditText et_pass = (EditText) findViewById(R.id.et_pass);
String name = et_name.getText().toString();
String pass = et_pass.getText().toString();
CheckBox cb = (CheckBox) findViewById(R.id.cb);
// 判断选框是否勾选
if (cb.isChecked()) {
//检查sd卡是否可用
// MEDIA_UNKNOW:不能识别sd卡
// MEDIA_REMOVED:没有sd卡
// MEDIA_UNMOUNTED:sd卡存在但是没有挂载
// MEDIA_MOUNTED:sd卡可用
if (Environment.getExternalStorageDirectory().equals(
Environment.MEDIA_MOUNTED)) {
// 引号内容是文件地址,外部存储空间
File file = new File("sdcard/info.txt");
// 使用API调用文件地址,获得sd卡真实路径
// File file = new File(Environment.getExternalStorageDirector(),"info.txt");
try {
FileOutputStream fos = new FileOutputStream(file);
fos.write((name + "##" + pass).getBytes());
fos.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
}
}else{
Toast.makeText(this, "sd卡不可用", Toast.LENGTH_SHORT).show();
}
}
Toast.makeText(this, "登陆成功", Toast.LENGTH_SHORT).show();
;
}
读操作:
与上文内部读操作类似,只是读取文件时的格式应该与外部写操作格式一样,并且判断sd卡是否可用。