Android写入文件到sdcard中

    xiaoxiao2021-04-14  41

    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权限。

    转载请注明原文地址: https://ju.6miu.com/read-669573.html

    最新回复(0)