简介
使用内部存储方式进行保存用户名和密码
内部存储空间 存在/data/data/<package name>/files下面,可以通过getFilesDir()获取到该路径
如果想在内部空间写入数据,只能写到自己的文件夹中,所以不需要在Manifest文件中添加权限
代码
登录并保存数据
public void login(View v) {
EditText et_name = (EditText) findViewById(R.id.et_name);
EditText et_pwd = (EditText) findViewById(R.id.et_pwd);
String name = et_name.getText().toString();
String pwd = et_pwd.getText().toString();
CheckBox cb = (CheckBox) findViewById(R.id.ch_save);
if (cb.isChecked()) {
// 内部存储空间 /data/data/<package name>/files下面
// 如果想在内部空间写入数据,只能写到自己的文件夹中,所以不需要在Manifest文件中添加权限
// File file = new File("/data/data/com.example.savenamepwd/files/info.txt");
File file = new File(getFilesDir(),"info.txt");
FileOutputStream fos = null;
try {
fos = new FileOutputStream(file);
fos.write((name + "##" + pwd).getBytes());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Toast.makeText(this, "登录成功", Toast.LENGTH_SHORT).show();
}载入数据到EditText
public void readFile() {
//File file = new File("/data/data/com.example.savenamepwd/files/info.txt");
File file = new File(getFilesDir(),"info.txt");
if (file.exists()) {
try {
FileInputStream fis = new FileInputStream("file");
// 把字节流转换为字符流
BufferedReader bf = new BufferedReader(new InputStreamReader(
fis));
// 读取txt文件里的用户名和密码
String text = bf.readLine();
String[] strs = text.split("##");
// 数据回显至输入框
EditText et_name = (EditText) findViewById(R.id.et_name);
EditText et_pwd = (EditText) findViewById(R.id.et_pwd);
et_name.setText(strs[0]);
et_pwd.setText(strs[1]);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}我们实际开发不会使用此种方式,进行保存用户名和密码,可以参考SharedPreference讲解。

这篇博客介绍了如何在Android应用中使用内部存储的File方式来保存和加载登录时的用户名和密码。通过getFilesDir()获取内部存储路径,无需额外权限即可在应用专属文件夹中读写数据。
1845

被折叠的 条评论
为什么被折叠?



