2015-09-10 23 views
0

我有一個.txt文件中有各種變量(每個都由一行分隔)。我需要讀取.txt文件並將其分配給txt文件中的相應變量。 無需在同一順序如何在Java中將文件內容分配到一個變量

input.txt中

int a=3; 
boolean b=true; 
String sr = "Hai"; 

我試過

int a; 
boolean b; 
String sr; 
String CurrentLine; 
br = new BufferedReader(new FileReader("C:\\input.txt")); 
while ((CurrentLine = br.readLine()) != null) { 
    \\ need to read assign variables to corresponding variables in test file 
} 

是可以申報變量文件和主(讀)?

+2

什麼不適合你的嘗試? – dotvav

+0

Integer.parseInt(currentLine)爲int,currentLine.equalsIgnoreCase(「true」)爲布爾值,curretLine爲String爲String數據類型 –

+0

@dotvav如何分配一個字符串到字符串和int到int ... – Ravichandra

回答

2

如果這是一種選擇,我建議你改變你的文件格式如下:

input.properties

a=3 
b=true 
sr=Hai 

,並使用如下代碼:

Properties prop = new Properties(); 
prop.load(new FileInputStream("intput.properties")); 
int a = Integer.parseInt(prop.getProperty("a", "0")); 
boolean b = Boolean.parseBoolean(prop.getProperty("b", "false")); 
String sr = prop.getProperty("sr"); 
0

可以做這樣的事情(但它是awfaul,脆弱的代碼沒有任何形式的異常處理):

if (CurrentLine.startsWith("boolean")) { 
     String str = CurrentLine.substring(0, CurrentLine.length()-1); 
     String[] sa = str.split("="); 
     b = Boolean.parseBoolean(sa[1].trim()); 
    } 
    else if (CurrentLine.startsWith("int")) 
    //... 

正如評論mentionend你應該使用一些結構化的文件格式,如果可能。

相關問題