2016-10-11 27 views
3

我有一個本地存儲ini file而我試圖解析如下:分析錯誤的ini文件「#」線

Ini ini = new Ini(new File("path/to/file")); 
System.out.println(ini.get("header", "key")); 

但我不斷收到指着線解析錯誤異常消息在ini文件(#)的註釋行之後。這就是我的ini文件看起來像:

File.ini

#Tue Oct 11 18:45:03 CST 2016 
 
PVIDNO=PALMUS-00001 
 
PVIDNo=SSI-1 
 
Authentication=VALID 
 
ModelNo=KD03816-B001 
 
PALMUS-ID=73364 
 
PV-ID=PALMUS-01

+1

哪裏級'Ini'從何而來?這不是Java標準庫中的類。通常你會使用類「Properties」來加載這種格式的文件。 – Jesper

+0

@Jesper忘了提及我使用ini4j。 –

+0

看看這個[點擊我](http://stackoverflow.com/a/190633/1577167)希望這可以幫助。 – BottleMan

回答

2

你可以做同樣的Properties

Properties p = new Properties(); 
p.load(new FileInputStream("user.props")); 
System.out.println("user = " + p.getProperty("DBuser")); 
System.out.println("password = " + p.getProperty("DBpassword")); 
System.out.println("location = " + p.getProperty("DBlocation")); 

在.ini文件是:

# this a comment 
! this a comment too 
DBuser=anonymous 
DBpassword=&8djsx 
DBlocation=bigone 
+0

雖然我在哪裏打電話或啓動ini文件?抱歉。新手在這裏。 –

+0

p.load()方法。 p.load(new FileInputStream(「user.props」)); – granmirupa

+0

這對我來說非常合適。謝謝! –

2

您正在使用一些燕麗是來自誰也不知道的地方; Ini-File解析器根本不喜歡包含「#comment」條目的.ini文件。

所以,你的選擇基本上是:

  1. 我忘了這第一,但也許「最好」的選擇:不使用「INI」文件;但改爲「財產」文件;這對Java應用程序來說是一個更「自然」的選擇。爲他們提供「內置」支持;嘿,「#評論」開箱即用。
  2. If Ini是「你自己的代碼」;那麼你讓你自己的代碼接受這樣的評論
  3. 如果Ini來自某個庫,那麼你檢查該庫是否允許影響解析過程以允許這樣的評論。

如果庫不允許這樣的特殊處理,你有另外兩個選擇:

  1. 尋找出一些其他的第三方庫文件
  2. 「對話」解析爲提供你正在使用的圖書館的人,並說服他們以某種方式讓他們的圖書館爲你工作。
+0

我檢查過圖書館,它確實允許#評論。儘管你會嘗試你所說的改變財產。謝謝! –

+0

歡迎您! – GhostCat

1

您是否嘗試過使用屬性?

創建配置:

屬性prop = new Properties(); OutputStream輸出= null;

try { 
     SaveSucessful = true; 
    output = new FileOutputStream("config.jar"); 

    // set the properties value 
    prop.setProperty("PVIDNO", "PALMUS-00001"); 

    // save properties to project root folder 
    prop.store(output, null); 

} catch (IOException io) { 
    io.printStackTrace(); 
} finally { 
    if (output != null) { 
     try { 
      output.close(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
    } 
    } 

讀取配置:

Properties prop = new Properties(); 
    InputStream input = null; 

    try { 
      LoadSucessful = true; 
     input = new FileInputStream("config.jar"); 

     // load a properties file 
     prop.load(input); 

     // get the property value and print it out 
     PlayerName = prop.getProperty("PVIDNO"); 

    } catch (IOException ex) { 
     ex.printStackTrace(); 
    } finally { 
     if (input != null) { 
      try { 
       input.close(); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
     } 
    } 

這應該很好地工作。

+0

您正在使用'.jar'擴展名?真的嗎? – fabian

+0

將嘗試使用屬性。雖然不太清楚.jar。 –

+0

使用任何你喜歡的擴展,.jar只是我用過的一個例子。 –