• Java 使用json 做配置文件


    概述

    经常会用到通过配置文件,去配置一些参数,java里面本来是有配置文件的,但是导入很麻烦的,自从我用了json之后,从此一切配置文件都见鬼去吧.

    1.下载gson解析json文件的jar包

        首先我们要导入一个解析json文件的jar包,下载连接如下所示:

    https://mvnrepository.com/artifact/com.google.code.gson/gson

    2.导入gson包到当前工程

    eclipse 下面鼠标选中 JRE System Libraries -> Build Path -> Configure Build Path找到 Libraries 选项卡,Add External JARs ,找到刚才下载的gson jar包 选择,导入到当前工程。

    3.读取json文件转换为字符串

    如下所示代码,方法入口参数为文件名,记得要带上路径

    public String readToString(String fileName) {
    	String encoding = "UTF-8";
    	File file = new File(fileName);
    	Long filelength = file.length();
    	byte[] filecontent = new byte[filelength.intValue()];
    	try {
    		FileInputStream in = new FileInputStream(file);
    		in.read(filecontent);
    		in.close();
    	} catch (FileNotFoundException e) {
    		e.printStackTrace();
    	} catch (IOException e) {
    		e.printStackTrace();
    	}
    	try {
    		return new String(filecontent, encoding);
    	} catch (UnsupportedEncodingException e) {
    		System.err.println("The OS does not support " + encoding);
    		e.printStackTrace();
    		return null;
    	}
    }
    

    4.解析字符串为java类

    解析为java类的过程是json序列化的过程,如下所示:

    public class ImportCfgFile{
    	public static  inicfg ini = new inicfg();
    	public ImportCfgFile(){
    		Gson gson = new Gson();
    		String str = ini.readToString("config.json");
    		try {
    			//str  = gson.toJson(ini);
    			//System.out.println("json 格式:"+str);
    			ini = gson.fromJson(str.trim(), inicfg.class);
    			//System.out.println("配置文件:
    "+str);
    		} catch (Exception e) {
    			System.out.println("配置文件读取失败,异常退出");
    			return ;
    		}
    
    	}
    }
    

    其中inicfg是一个用户定义的要和json文件对应的类,写配置文件最好先按照inicfg类的方式生成类似的json字符串,使用str = gson.toJson(ini) ,记得要对ini初始化才可以,这样我们拷贝打印出来的消息到config.json文件里面,就不会抛出解析失败的异常了

  • 相关阅读:
    BUUCTF--[GUET-CTF2019]number_game
    36D杯CTF Re WP
    BUUCTF--[GWCTF 2019]re3
    虎符网络安全赛道 Re Game
    Python ZIP压缩文件破解
    合唱队, 华为
    字符串排序, 华为
    称砝码, 华为
    迷宫问题, 华为
    Sudoku , 华为
  • 原文地址:https://www.cnblogs.com/memorypro/p/9518354.html
Copyright © 2020-2023  润新知