您的位置:首页 > 移动开发 > Android开发

Android保存用户名和密码

2016-07-06 14:51 274 查看
本文转自:http://www.2cto.com/kf/201401/272336.html

我们不管在开发一个项目或者使用别人的项目,都有用户登录功能,为了让用户的体验效果更好,我们通常会做一个功能,叫做保存用户,这样做的目地就是为了让用户下一次再使用该程序不会重新输入用户名和密码,这里我使用3种方式来存储用户名和密码

1、通过普通 的txt文本存储

2、通过properties属性文件进行存储

3、通过SharedPreferences工具类存储

第一种:
/**
* 保存用户名和密码的业务方法
*
* @param username
* @param password
* @return
*/
public static boolean saveUserInfo(String username, String password) {
try {
// 使用当前项目的绝对路径
File file = new File("data/data/com.example.android_file_handler/info.txt");
// 创建输出流对象
FileOutputStream fos = new FileOutputStream(file);
// 向文件中写入信息
fos.write((username + "##" + password).getBytes());
// 关闭输出流对象
fos.close();
return true;
} catch (Exception e) {
throw new RuntimeException();
}
}

   这里写的路径是当前项目的绝对路径,这样做是有缺陷的,比如你将项目路径改了,这里的路径就获取就失败了,所以Android提供了通过上下文一个方法获取当前项目的路径

public static boolean saveUserInfo(Context context, String username,
String password) {
try {
// 使用Android上下问获取当前项目的路径
File file = new File(context.getFilesDir(), "userinfo.txt");
// 创建输出流对象
FileOutputStream fos = new FileOutputStream(file);
// 向文件中写入信息
fos.write((username + "##" + password).getBytes());
// 关闭输出流对象
fos.close();
return true;
} catch (Exception e) {
throw new RuntimeException();
}
}
上面这两个方法都是存储用户名和密码,接下来是获取用户名和密码

/**
* 获取普通txt文件信息
*
* @param context
* @return
*/
public static Map<string, object=""> getTxtFileInfo(Context context) {
try {
// 创建FIle对象
File file = new File(context.getFilesDir(), "userinfo.txt");
// 创建FileInputStream对象
FileInputStream fis = new FileInputStream(file);
// 创建BufferedReader对象
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
// 获取文件中的内容
String content = br.readLine();
// 创建Map集合
Map<string, object=""> map = new HashMap<string, object="">();
// 使用保存信息使用的##将内容分割出来
String[] contents = content.split("##");
// 保存到map集合中
map.put("username", contents[0]);
map.put("password", contents[1]);
// 关闭流对象
fis.close();
br.close();
return map;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}</string,></string,></string,>


这里我将获取到的内容封装到Map集合中,其实使用普通的txt文本存储用户名和密码是有缺陷的,这里我是通过“##”来分割用户名和密码的,那么如果用户在密码中的字符又包含了“#”这个特殊符号,那么最后在获取时,则获取不倒原来保存的信息,所以个人认为第二种方法就可以解决这个问题

第二种:

使用属性文件保存用户名和密码
/**
* 使用属性文件保存用户的信息
*
* @param context 上下文
* @param username 用户名
* @param password  密码
* @return
*/
public static boolean saveProUserInfo(Context context, String username,
String password) {
try {
// 使用Android上下问获取当前项目的路径
File file = new File(context.getFilesDir(), "info.properties");
// 创建输出流对象
FileOutputStream fos = new FileOutputStream(file);
// 创建属性文件对象
Properties pro = new Properties();
// 设置用户名或密码
pro.setProperty("username", username);
pro.setProperty("password", password);
// 保存文件
pro.store(fos, "info.properties");
// 关闭输出流对象
fos.close();
return true;
} catch (Exception e) {
throw new RuntimeException();
}
}
读取属性文件

在主方法中调用即可
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: