1. 程式人生 > >Java讀取ini方法

Java讀取ini方法

第一接觸ini配置檔案,這裡記錄兩種讀取方式:

  1. 通過Properties讀取ini檔案
    這種方式網上使用的最多也最方便,不過讀取順序會有變化。
/**
     * 最簡單的讀取ini方法 但是讀取的順序會變化
     * 
     * @param file
     * @return
     * @throws Exception
     */
    public String read(String file) throws Exception {
        Properties pro = new Properties();
        StringBuffer sb = new
StringBuffer(); InputStream in = new BufferedInputStream(new FileInputStream(file)); pro.load(in); Set keyValue = pro.keySet(); for (Iterator it = keyValue.iterator(); it.hasNext();) { String key = (String) it.next(); sb.append(key + ":" + pro.get(key) + "\n"
); // System.out.println(key + " "+ pro.get(key)); } return sb.toString(); }
  1. 自己寫的讀取方式,其中將ini註解變成#的方式輸出,並根據ini每個節劃分,組合“節_key”的方式輸出。
private static HashMap<String, String> itemsMap = new HashMap<String, String>();
    private static String currentSection = ""
;//節名稱 /** * 讀取ini 檔案 * @param file 檔案路徑 * @return String 返回所有內容 * @throws Exception */ public String read2(String file) throws Exception { StringBuffer sb = new StringBuffer(); BufferedReader bf = new BufferedReader(new InputStreamReader( new FileInputStream(file), "GB2312")); String line = null; while ((line = bf.readLine()) != null) { line = line.trim(); if ("".equals(line)) continue; if (line.startsWith("[") && line.endsWith("]")) { currentSection = line.substring(1, line.length() - 1); sb.append(currentSection+"\r\n"); }else if(line.startsWith(";")){ String str = "#"+line.substring(1); sb.append(str+"\r\n"); }else { int index = line.indexOf("="); if (index != -1) { String key = currentSection + "_" + line.substring(0, index); String value = line.substring(index + 1, line.length()); itemsMap.put(key, value); sb.append(key+"="+value+"\r\n"); } } } return sb.toString(); }

暫時總結這一點點,後續用到在新增。