2011-09-11 24 views
1

我在一家.dat文件中存儲這些數據:如何從文件中檢索指定的數據?

data = date + ": " + y + "L/100KM "+ " " + value1 + "dt "+ value2 + "KM\n"; 

每一行都有日期,Y,值1和值2的值不同。 我想檢索每一行的變量value1。如何瀏覽文件並提取所有行的這個變量。我在我的項目中解決了這個問題。感謝您的幫助。 編輯:例: 我有存儲在文件中這3個DATAS:

11/09: 5.8L/100KM 20dt 250KM 
12/09: 6.4L/100KM 60dt 600KM 
13/09: 7.5L/100KM 50dt 543KM 

在這種情況下,我想找回20dt,60dt和50dt。

+0

給我們幾行例子。 – aioobe

+0

@aioobe:請參閱我編輯的帖子。 – androniennn

+0

我的解決方案應該沒問題。 – aioobe

回答

2

下面是使用正則表達式一個建議:

String line = "12/09: 6.4L/100KM 60dt 600KM"; 

Pattern p = Pattern.compile("(\\d+)dt"); 
Matcher m = p.matcher(line); 

if (m.find()) 
    System.out.println(m.group(1)); // prints 60 

如果你有幾行遍歷,你會使用,例如一個new BufferedReader(new FileReader("youfile.dat"))並做類似

String line; 
while ((line = br.nextLine()) != null) { 
    Matcher m = p.matcher(line); 
    if (m.find()) 
     process(m.group(1)); 
} 

您也可以使用line.split(" ")並選擇3:rd元素:

String line = "12/09: 6.4L/100KM 60dt 600KM"; 
String dtVal = line.split(" ")[2]; 

// Optional: Remove the "dt" part. 
dtVal = dtVal.substring(0, dtVal.length() - 2); 

System.out.println(dtVal); 
+0

好的,結果將被「分組」。如果我想將所有回溯值存儲在該值的String []中,我該怎麼辦?String [] verlabels = new String [] {}' – androniennn

+1

創建'ArrayList list',並執行'list。在每次迭代中添加(dtVal)'。 – aioobe

+0

還有一個問題:如何檢索日期? 'line.split(?)'?尋找你的迴應。 – androniennn