2014-01-12 57 views
0

我的程序需要從多行.ini文件中讀取,我已經知道它讀取以#開頭的每一行並打印它。但我只想記錄=號後的值。這裏的文件應該是什麼樣子:Buffered Reader找到特定的行分隔符char然後讀取該行

#music=true 
#Volume=100 
#Full-Screen=false 
#Update=true 

這是我想它打印:

true 
100 
false 
true 

這是我的代碼,目前我使用:

@SuppressWarnings("resource") 
public void getSettings() { 
    try { 
     BufferedReader br = new BufferedReader(new FileReader(new File("FileIO Plug-Ins/Game/game.ini"))); 
     String input = ""; 
     String output = ""; 
     while ((input = br.readLine()) != null) { 
      String temp = input.trim(); 
      temp = temp.replaceAll("#", ""); 
      temp = temp.replaceAll("[*=]", ""); 
      output += temp + "\n"; 
     } 
     System.out.println(output); 
    }catch (IOException ex) {} 
} 

我m不知道是否replaceAll(「[* =]」,「」);真正意味着什麼,或者只是爲了尋找所有這些字符。任何幫助表示讚賞!

回答

1

嘗試以下:

if (temp.startsWith("#")){ 
    String[] splitted = temp.split("="); 
    output += splitted[1] + "\n"; 
} 

說明: 要處理線只與期望的字符使用String#startsWith方法開始。當你有字符串提取值時,String#split會將給定的文本與你給出的作爲方法參數的字符分開。所以在你的情況下,=字符之前的文本將位於0的位置,你想要打印的文本將在位置1

另請注意,如果您的文件包含許多以#開頭的行,應該明智地不要將字符串連接在一起,而是使用StringBuilder/StringBuffer將字符串添加到一起。

希望它有幫助。

0

如下所示,最好使用StringBuffer,而不是使用+ =和String。另外,避免在循環內聲明變量。請看看我是如何在循環之外完成的。據我所知,這是最好的做法。

StringBuffer outputBuffer = new StringBuffer(); 
String[] fields; 
String temp; 
while((input = br.readLine()) != null) 
{ 
    temp = input.trim(); 
    if(temp.startsWith("#")) 
    { 
     fields = temp.split("="); 
     outputBuffer.append(fields[1] + "\n"); 
    } 
} 
+0

如果僅在一個線程中訪問對象,則使用'StringBuilder'優先於'StringBuffer',否則您將爲效率降低而支付'StringBuffer'的線程安全性。 – neuralmer

相關問題