java如何读写json文件

java如何读写json文件

  在实际项目开发中,有时会遇到一些全局的配置缓存,最好的做法是配置redis数据库作为数据缓存,而当未有配置redis服务器时,读取静态资源文件(如xml、json等)也是一种实现方式,但是这有一个弊端,因为作为静态资源存储在站内势必就导致信息的安全性很低,所以如果采用这种方式则建议记录一些安全要求很低的配置属性,当然最好的做法就是使用redis缓存技术。下面就json文件的读写进行进一步说明。

  1、json通用文件读取方法,这个方法会返回map对象:

   /**
     * json读取
     * 
     * @param request
     * @param path
     * @return
     */
    public static List JsonRead(HttpServletRequest request, String path) {
        List maps = null;
        String dir = request.getSession().getServletContext().getRealPath(path);
        System.out.println(path);
        System.out.println(dir);
        if (dir == null) {
            System.out.println("找不到数据");
            return null;
        }
        try {
            File file = new File(dir);
            if (!file.exists()) {
                file.createNewFile();
            }
            String str = FileUtils.readFileToString(file, "UTF-8");
            maps = (List) JSONArray.fromObject(str);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return maps;
    };

  2、json指定文件读取方法,这个方法是针对特定的json文件,返回值也是特定的实体对象:

    首先要先定义实体类(我这里就拿项目中一个demo做示例):  

package com.net.entity;
/**
 * 系统广告图片
 * @author zhangdi
 *
 */
public class SysAdverImg {

    private int id;//方便后期数据库拓展
    private String img11;//首页广告1
    private String img12;//首页广告2
    private String img13;//首页广告3
    private String img21;//积分广告1
    private String img22;//积分广告2
    private String img23;//积分广告3
    private String url11;//首页广告链接1
    private String url12;//首页广告链接2
    private String url13;//首页广告链接3
    private String url21;//积分广告链接1
    private String url22;//积分广告链接2
    private String url23;//积分广告链接3
    
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getImg11() {
        return img11;
    }
    public void setImg11(String img11) {
        this.img11 = img11;
    }
    public String getImg12() {
        return img12;
    }
    public void setImg12(String img12) {
        this.img12 = img12;
    }
    public String getImg13() {
        return img13;
    }
    public void setImg13(String img13) {
        this.img13 = img13;
    }
    public String getImg21() {
        return img21;
    }
    public void setImg21(String img21) {
        this.img21 = img21;
    }
    public String getImg22() {
        return img22;
    }
    public void setImg22(String img22) {
        this.img22 = img22;
    }
    public String getImg23() {
        return img23;
    }
    public void setImg23(String img23) {
        this.img23 = img23;
    }
    
}

    第二步:针对这个特定实体类来写特定的json文件读取方法:

/*
     * 取出广告图片内容,填充对象
     */
    public SysAdverImg findSysAdverImg(String path) {
        SysAdverImg config = new SysAdverImg();
        String sets = ReadFile(path);// 获得json文件的内容
        System.out.println(sets);
        // 去掉json中的[]
        sets = sets.substring(1, sets.length() - 1);
        System.out.println(sets);
        JSONObject jo = JSONObject.fromObject(sets);// 格式化成json对象
        System.out.println(jo.toString());
        config.setId(Integer.valueOf(jo.getString("id")));
        config.setImg11(jo.getString("img11"));
        config.setImg12(jo.getString("img12"));
        config.setImg13(jo.getString("img13"));
        config.setImg21(jo.getString("img21"));
        config.setImg22(jo.getString("img22"));
        config.setImg23(jo.getString("img23"));
        config.setUrl11(jo.getString("url11"));
        config.setUrl12(jo.getString("url12"));
        config.setUrl13(jo.getString("url13"));
        config.setUrl21(jo.getString("url21"));
        config.setUrl22(jo.getString("url22"));
        config.setUrl23(jo.getString("url23"));
        return config;
    }

    这里调用的ReadFile方法如下:

// 读文件,返回字符串
    public String ReadFile(String path) {
        File file = new File(path);
        BufferedReader reader = null;
        String laststr = "";
        try {
            // System.out.println("以行为单位读取文件内容,一次读一整行:");
            reader = new BufferedReader(new FileReader(file));
            String tempString = null;
            int line = 1;
            // 一次读入一行,直到读入null为文件结束
            while ((tempString = reader.readLine()) != null) {
                // 显示行号
                System.out.println("line " + line + ": " + tempString);
                laststr = laststr + tempString;
                line++;
            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e1) {
                }
            }
        }
        return laststr;
    }

  3、特定的json文件修改(即对json文件进行写的操作)

    首先是编写文件写的通用操作方法:  

    // 把json格式的字符串写到文件
    public boolean writeFile(String filePath, String sets) {
        FileWriter fw;
        try {
            fw = new FileWriter(filePath);
            PrintWriter out = new PrintWriter(fw);
            out.write(sets);
            out.println();
            fw.close();
            out.close();
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }

    }

    再就特定的实体类执行写的操作(这里还是以第二步的实体类为例):

    /**
     * 系统后台更新广告图片
     * @param img
     * @param type
     * @param request
     * @param resq
     * @return     200 更新成功 
     *                         501 上传图片为空 
     *                         502 上传类型为空 
     *                         503 无法读取json文件 
     *                         504 错误的类型 
     *                         505 json文件更新失败
     *                         506 上传链接为空
     */
    @RequestMapping(value="updateAdverImgConfig" ,method=RequestMethod.POST,
            produces="application/json;charset=utf-8")
    @ResponseBody
public String updateAdverImgConfig(
            @RequestParam("img")String img,
            @RequestParam("url")String url,
            @RequestParam("type")Integer type,
            HttpServletRequest request,
            HttpServletResponse resq){
        if(img==null||img==""){
            return "501";//图片为空
        }
        if(type==null){
            return "502";//类型为空
        }
        if(url==null||url==""){
            return "506";//链接为空
        }
        //系统路径
        String pathRoot = request.getSession().getServletContext().getRealPath("");
        //网站配置路径
        String baseRoot = jsonUtil.findSysConfig(pathRoot+"/config/config.json").getBaseUrl();
        //读取出源文件
        SysAdverImg sai = new SysAdverImg();
        try {
            sai = jsonUtil.findSysAdverImg(pathRoot+"/config/adver_img.json");
        } catch (Exception e) {
            return "503";//无法读取源文件
        }
        //处理传过来的base64
        // 这里处理传过来的广告图片base64
        if(img!=""||img!=null){
             //图片的存储路径
            String newImaPath = File.separator +"img"+File.separator+"imgZip" + File.separator;
            String path = newImaPath+UtilNet.getRandomNumberString(24)+".jpg";
            //截取字符串,将data:image/jpg;base64去掉,取剩余的字符串
            String imgType = img.substring(11, 14);
            if(imgType.equals("jpe")){
                img = img.substring(23);
            }else if(imgType.equals("jpg")||imgType.equals("png")){
                img = img.substring(22);
            }else if(imgType.equals("gif")){
                //data:image/gif;base64,R0l
                img = img.substring(22);
            }else{
                img = img.substring(22);
            }
            //进行解码
            ImageBase64Util.GenerateImage(img, path,request);
            //赋值成绝对路径
            System.out.println(path);
            path = baseRoot+path;
            System.out.println(path);
            // 路径赋值
            switch (type) {
            case 0://首页广告1
                sai.setImg11(path);
                sai.setUrl11(url);
                break;
            case 1://首页广告2
                sai.setImg12(path);
                sai.setUrl12(url);
                break;
            case 2://首页广告3
                sai.setImg13(path);
                sai.setUrl13(url);
                break;
            case 3://积分广告1
                sai.setImg21(path);
                sai.setUrl21(url);
                break;
            case 4://积分广告2
                sai.setImg22(path);
                sai.setUrl22(url);
                break;
            case 5://积分广告3
                sai.setImg23(path);
                sai.setUrl23(url);
                break;
            default:
                return "504";
            }
        }
        //写入json文件中        
        String config = "[{"+"\n"
                                        +" \"" +"id"+"\" "+":"+" \""+sai.getId()+"\","+"\n"
                                        +" \"" +"img11"+"\" "+":"+" \""+sai.getImg11()+"\","+"\n"
                                        +" \"" +"img12"+"\" "+":"+" \""+sai.getImg12()+"\","+"\n"
                                        +" \"" +"img13"+"\" "+":"+" \""+sai.getImg13()+"\","+"\n"
                                        +" \"" +"img21"+"\" "+":"+" \""+sai.getImg21()+"\","+"\n"
                                        +" \"" +"img22"+"\" "+":"+" \""+sai.getImg22()+"\","+"\n"
                                        +" \"" +"img23"+"\" "+":"+" \""+sai.getImg23()+"\","+"\n"
                                        +" \"" +"url11"+"\" "+":"+" \""+sai.getUrl11()+"\","+"\n"
                                        +" \"" +"url12"+"\" "+":"+" \""+sai.getUrl12()+"\","+"\n"
                                        +" \"" +"url13"+"\" "+":"+" \""+sai.getUrl13()+"\","+"\n"
                                        +" \"" +"url21"+"\" "+":"+" \""+sai.getUrl21()+"\","+"\n"
                                        +" \"" +"url22"+"\" "+":"+" \""+sai.getUrl22()+"\","+"\n"
                                        +" \"" +"url23"+"\" "+":"+" \""+sai.getUrl23()+"\""+"\n"
                                        +"}]";
        boolean isUpdate = jsonUtil.writeFile(pathRoot+"/config/adver_img.json", config);
        if(isUpdate){
            return "200";
        }else{
            return "505";
        }
    }    
}

至此关于json文件的读写就完成了

 

posted on 2017-09-25 09:37 < /> 阅读( ...) 评论( ...) 编辑 收藏

转载于:https://www.cnblogs.com/zhangdiIT/p/7590472.html

你可能感兴趣的:(java如何读写json文件)