最近有個(gè)需求要去將一個(gè)屬性值轉(zhuǎn)換為其對(duì)應(yīng)的代號(hào)耘成,本來(lái)想直接在spring中以注入Map的形式去匹配key的值得出相應(yīng)的value值,但是要匹配的分類和每個(gè)分類中的類別是在太多,就決定使用JSON的方式掌呜,將其都記錄在文件里,然后寫個(gè)工具類在其static代碼塊中做讀取工具坪哄,這樣在生命周期內(nèi)就可以只讀取一次文件了质蕉,減少系統(tǒng)消耗(理解不深我是這么想的)
但是問(wèn)題出現(xiàn)了,我按照傳統(tǒng)的讀取文件方式在測(cè)試時(shí)可以正確讀取但是啟動(dòng)javaWeb項(xiàng)目后直接報(bào)錯(cuò)了翩肌,下邊是一開(kāi)始的代碼:
static {
System.out.println("1");
File file=null;
BufferedReader reader=null;
String lastStr="";
try {
String path=ConvertType2Code.class.getClassLoader().getResource("config/codeDirec.json").getPath();
file=new File(path);
reader=new BufferedReader(new FileReader(file));
String tempStr=null;
while ((tempStr=reader.readLine())!=null){
lastStr+=tempStr;
}
reader.close();
}catch (Exception e){
e.printStackTrace();
}finally {
if(reader!=null){
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
jsonObject=JSONObject.fromObject(lastStr);
}
從代碼上來(lái)說(shuō)沒(méi)有毛病的好不好 但是一開(kāi)始調(diào)用就說(shuō)累無(wú)法初始化呢模暗,然后classNotDef這種的錯(cuò)。
最后看了hibernate 還有別的讀取.property
文件代碼用了另一個(gè)方式念祭,發(fā)現(xiàn)就可以了 找了半天也沒(méi)發(fā)現(xiàn)原因兑宇,望有知道的道友解答下
static {
String lastStr="";
try{
InputStream inputStream=ConvertType2Code.class.getClassLoader().getResourceAsStream("config/codeDirec.json");
BufferedReader bf=new BufferedReader(new InputStreamReader(inputStream,"utf-8"));
String tempStr=null;
while ((tempStr=bf.readLine())!=null){
lastStr+=tempStr;
}
bf.close();
}catch (Exception e){
e.printStackTrace();
}
jsonObject=JSONObject.fromObject(lastStr);
}