Android写入文件到sdcard中

public class UserInfoUtils {
    // 保存用户名和密码的业务方法
    public static boolean saveInfo(String username, String pwd) {

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

            //创建file类指定我们要存储数据的位置 把数据保存到sd卡

            String sdPath = Environment.getExternalStorageDirectory().getPath();

            File file = new File(sdPath, "haha.txt");

            //2 创建一个文件输出流
            FileOutputStream fos = new FileOutputStream(file);

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

    // 读取用户的信息
    public static Map<String ,String> readInfo() {
        try {
            //1 定义Map
            Map<String, String> maps = new HashMap<String, String>();

            String sdPath = Environment.getExternalStorageDirectory().getPath();

            File file = new File(sdPath, "haha.txt");

            FileInputStream fis = new FileInputStream(file);

            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;
        }
    }
}

在进行了以上操作之后,还要记得在AndroidManifest.xml中配置权限

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
然后就可以了。


中间出了一个小插曲,运行APP后,保存数据失败,但在真机中有效。

最后发现是android7.0系统的虚拟机在安装APP后要在设置里手动赋予APP权限。




  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值