概述
經常會用到通過配置文件,去配置一些參數,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("配置文件:\r\n"+str);
} catch (Exception e) {
System.out.println("配置文件讀取失敗,異常退出");
return ;
}
}
}
其中inicfg是一個用戶定義的要和json文件對應的類,寫配置文件最好先按照inicfg類的方式生成類似的json字符串,使用str = gson.toJson(ini) ,記得要對ini初始化才可以,這樣我們拷貝打印出來的消息到config.json文件里面,就不會拋出解析失敗的異常了
