Android通过上下文获取常用目录context.openFileOutput();

本文介绍了一个实用的工具类UserInfoUtils,它提供了在Android应用中保存和读取用户名及密码的方法。通过使用Context.openFileOutput和Context.openFileInput方法,可以将数据安全地保存在应用私有目录下。此外,还介绍了如何利用FileInputStream和BufferedReader从文件中读取这些信息。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

public class UserInfoUtils {
    // 保存用户名和密码的业务方法
    public static boolean saveInfo(Context context, String username, String pwd) { //在原有函数的基础上传一个上下文进来,因为我们要用到上下文,所以谁调用谁传。

        try {
            String result = username + "##" + pwd;

            /*2 通过传进来的上下文获取FileOutputStream,
			第一个参数,代表文件名称,注意这里的文件名称不能包括任何的/或者/这种分隔符,只能是文件名 
                        该文件会被保存在/data/data/应用名称/files/infoo.txt 
		MODE_PRIVATE 私有(只能创建它的应用访问) 重复写入时会文件覆盖                      
    		       	MODE_APPEND  私有   重复写入时会在文件的末尾进行追加,而不是覆盖掉原来的文件              *  
       		        MODE_WORLD_READABLE 公用  可读              *          
  			MODE_WORLD_WRITEABLE 公用 可读写 
		
		*/
            FileOutputStream fos = context.openFileOutput("infoo.txt", Context.MODE_PRIVATE); 

            fos.write(result.getBytes());
            fos.close();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    // 读取用户的信息
    public static Map<String ,String> readInfo(Context context) { // 通过函数参数方式,传进来一个上下文
        try {
            //1 定义Map
            Map<String, String> maps = new HashMap<String, String>();
            File file = new File("data/data/com.example.a10_login/info.txt");
            FileInputStream fis = context.openFileInput("infoo.txt");
            BufferedReader bufr = new BufferedReader(new InputStreamReader(fis));
            String content = bufr.readLine(); // 读取数据

            // 切割字符串 封装到map集合中
            String[] splits = content.split("##");
            String name = splits[0];
            String pwd = splits[1];
            // 把name 和 pwd 放入map中
            maps.put("name", name);
            maps.put("pwd", pwd);
            fis.close();
            return maps;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值