2013-06-12 55 views
0

我有以下代碼解析ini文件和使用掃描器類

public static void main(String[] args) throws FileNotFoundException, IOException { 

    Scanner br = new Scanner(new FileReader("/home/esunmes/NetBeansProjects/random/src/random/something.config")); 
    HashMap map = new HashMap(); 
    String line; 
    String temp2; 
    while (br.hasNextLine()) { 
     line = br.next(); 
     Scanner scan = new Scanner(new FileReader("/home/esunmes/NetBeansProjects/random/src/random/inifile.config")); 
     while (scan.hasNextLine()) { 
      temp2 = (String) scan.next(); 
      if (temp2.equals(line)) { 
       Scanner scn = new Scanner(temp2); 
       String string; 
       while (scn.hasNextLine() && ((string = scn.next()) != "\n")) { 
        String[] temp3 = string.split("//="); 
        if (temp3.length > 1) { 
         String key = temp3[0]; 
         String value = temp3[1]; 
         map.put(key, value);// TODO code application logic here 
        } 
       } 
      } 
     } 
    } 
    Set set = map.entrySet(); 
    Iterator iter = set.iterator(); 
    while (iter.hasNext()) { 
     Map.Entry maps = (Map.Entry) iter.next(); 
     String key = (String) maps.getKey(); 
     String value = (String) maps.getValue(); 
     System.out.println("key:" + key + " value" + value); 
    } 
} 

問題存儲在HashMap中的值中兩個配置文件是 1.inifile.config

section1 
key1=1 
key2=2 

section2 
key4=4 
key5=5 

section3 
key6=6 
key3=3 

section4 
key7=7 

section5 
key8=8 

section6 
key9=9 

section7 
key10=10 

section8 
key11=11 

2.something.config

section1 
section2 
section3 
section4 
section8 

第一配置文件具有樣品日誌和第二個有要提取的部分的名稱

地圖應包含鍵值對,但他們不 和地圖出來是空的。可以有人請花時間來分析這...它真的很重要

回答

0

有在你的代碼的幾個問題:

  • 掃描儀SCN =新的掃描儀(TEMP2);

您只需使用掃描,您已經創建的,爲什麼你創建一個字符串的新的掃描儀?

  • string.split( 「// =」)

它應該是string.split("="),你不需要逃避"=",即使它需要逃生時,應該\\//

  • hasNext()應遵循與next()hasNextLine()應遵循與nextLine(),你不應該使用hasNextLine()然後使用next()

因此,代碼應該是

Scanner br = new Scanner(new FileReader("file2")); 
HashMap map = new HashMap(); 
String line; 
String temp2; 
while (br.hasNextLine()) { 
    line = br.nextLine(); 
    Scanner scan = new Scanner(new FileReader("file1")); 
    while (scan.hasNextLine()) { 
     temp2 = (String) scan.nextLine(); 
     if (temp2.equals(line)) { 
      //Scanner scn = new Scanner(temp2); 
      String string; 
      while (scan.hasNext() && ((string = scan.next()) != "\n")) { 
       String[] temp3 = string.split("="); 
       if (temp3.length > 1) { 
        String key = temp3[0]; 
        String value = temp3[1]; 
        map.put(key, value);// TODO code application logic 
             // here 
       } 
      } 
     } 
    } 
} 
Set set = map.entrySet(); 
Iterator iter = set.iterator(); 
while (iter.hasNext()) { 
    Map.Entry maps = (Map.Entry) iter.next(); 
    String key = (String) maps.getKey(); 
    String value = (String) maps.getValue(); 
    System.out.println("key:" + key + " value" + value); 
}