读、写指定SD卡路劲的json文件

前言:以下一读一写两个方法都是从“E家”总结而来,很容易看,也很容易用,将里面的路径换成自己的,就可以了。

/**
     * 读取模块CubeModule.json
     * @param m
     * @return
     */
    public String readCubeModuleJson(CubeModule m) {
        if (m == null) return null;
        String result = null;
        if (Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {
            File s = new File(URL.HtmlPath + "/" + m.getIdentifier() + "/CubeModule.json");
            try {
                FileInputStream in = new FileInputStream(s);
                // 获取文件的字节数
                int lenght = in.available();
                // 创建byte数组
                byte[] buffer = new byte[lenght];
                // 将文件中的数据读到byte数组中
                in.read(buffer);
                result = EncodingUtils.getString(buffer, "UTF-8");
            } catch (Exception e) {
                Log.i("模块", e.getMessage());
            }
        }
        return result;
    }

    /**
     * 写文件。
     *
     * @param json
     * @return
     */
    public boolean writeToJsonFile(String identifier, String json) {
        Boolean flag = false;
        // 获取sd卡目录
        File file = null;
        OutputStream output = null;
        try {
            file = new File(URL.HtmlPath + "/" + identifier + "/");
            if (!file.exists()) {
                file.mkdirs(); // 创建文件夹
            }
            file = new File(URL.HtmlPath + "/" + identifier + "/CubeModule.json");
            output = new FileOutputStream(file);
            output.write(json.getBytes());
            output.flush();
            flag = true;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                output.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return flag;
    }
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 179,782评论 25 708
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 136,868评论 19 139
  • 苦苦寻觅着一个可以让思想在文海中泛滥的APP,终于遇到了“简书”! 下面略列几条: 1.交流性!这是我最为动容之一...
    简称nice阅读 284评论 3 2
  • 漏接了邮局小哥来电,赶紧打回去,丫:我已经走了,明天再送。我:啊,你电话不是两分钟前打的吗?丫:我一般一次打不通就...
    偷影子的人Renaissanc阅读 227评论 1 1
  • 药方 第三十九味 林君的爸爸出院那天,她正认真的用笔记录医生交代的——马来酸依那普利、阿托伐他汀、阿司匹林、xx缓...
    九仙月阅读 822评论 2 0

友情链接更多精彩内容