最近有個需求要去將一個屬性值轉(zhuǎn)換為其對應的代號,本來想直接在spring中以注入Map的形式去匹配key的值得出相應的value值,但是要匹配的分類和每個分類中的類別是在太多,就決定使用JSON的方式,將其都記錄在文件里,然后寫個工具類在其static代碼塊中做讀取工具,這樣在生命周期內(nèi)就可以只讀取一次文件了,減少系統(tǒng)消耗(理解不深我是這么想的)
但是問題出現(xiàn)了,我按照傳統(tǒng)的讀取文件方式在測試時可以正確讀取但是啟動javaWeb項目后直接報錯了,下邊是一開始的代碼:
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);
}
從代碼上來說沒有毛病的好不好 但是一開始調(diào)用就說累無法初始化呢,然后classNotDef這種的錯。
最后看了hibernate 還有別的讀取.property文件代碼用了另一個方式,發(fā)現(xiàn)就可以了 找了半天也沒發(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);
}