Android 把数据保存到本地,列表显示文件以及读取的工具类


    /**
     * 写入json进入文本
     *
     * @param content  需要写入的文本
     * @param filePath txt文本名字
     */
    public static void writeToFile(String content, String filePath) {

        try {
            // 创建 FileWriter 对象,指定文件路径
            FileWriter writer = new FileWriter(Contans.BASE_PATH + "/" + filePath + ".txt");
            // 写入字符串
            writer.write(content);
            // 关闭 FileWriter
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * 获取 healforce文件夹下的名称
     *
     * @param
     */
    public static List<String> getFilesNames() {
        List<String> lists = new ArrayList<>();

        File[] files = new File(Contans.BASE_PATH).listFiles();
        if (files != null) {
     //       Arrays.sort(files);
            Arrays.sort(files, (file1, file2) -> -file1.getName().compareToIgnoreCase(file2.getName()));
            for (File file : files) {
                if (file.isFile()) {
                    if (file.getName().endsWith(".txt")) {
                        lists.add(file.getName().substring(0, file.getName().length() - 4)); // 去掉.txt
                    }

                }
            }
        }
        return lists;
    }




    /**
     * 获取某一个文件的信息
     *
     * @param filePath
     * @return
     */
    public static String readFileInfo(String filePath) {

        StringBuilder fileInfo = new StringBuilder();
        try (BufferedReader reader = new BufferedReader(new FileReader(Contans.BASE_PATH + "/" + filePath+".txt"))) {
            String line;
            while ((line = reader.readLine()) != null) {
                fileInfo.append(line).append("\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
        return fileInfo.toString();
    }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值