2016-11-21 123 views
1

我使用一個按鈕來保存用戶輸入到一個文本文件,現在我想檢索它來做一個計算。 正在更新文本文件並添加新值。 下面是一個例如文本文件的樣子:Java:如何從文本文件中只讀取int數據來執行計算?

  1. 週一:週二1:2 wednessday:3

...等

當有一個新的輸入它將被添加,所以 更新的文本文件看起來像這樣:

  1. 週一:1星期二:2 wednessday:3
  2. 星期一:4星期二:1個wednessday:3
  3. 星期一:6星期二:5 wednessday:6
  4. 星期一:7週二:6 wednessday:5

基本上我想比較新的輸入和以前的輸入。 如何從最新和最後輸入中只檢索所有整數?

還是應該用excel?

這裏是我的代碼:

try (
    InputStream fs = new FileInputStream("data.txt"); 
    // not sure how to use the Charset.forname 
    InputStreamReader isr = new InputStreamReader(fs, Charset.forName("UTF-8")); 
    BufferedReader br = new BufferedReader(isr)) { 
    for (String line1 = br.readLine(); line1 != null; line = br.readLine()) { 
     comp = line1 - line2; //line1 being current line(4) and line2 being the previous(3) 
    } 
} 
+0

你確定你粘貼的代碼是正確的嗎? –

+0

「最新」的標準是什麼? –

+0

@TimothyTruckle最新是第4行,最後是第3行 –

回答

1

簡單:

  1. 通過僅保留最後2行閱讀您的文件,
  2. 然後使用正則表達式提取整數。

相應的代碼:

try (
    InputStream fs = new FileInputStream("data.txt"); 
    InputStreamReader isr = new InputStreamReader(fs, StandardCharsets.UTF_8); 
    BufferedReader br = new BufferedReader(isr)) { 
    // Previous line 
    String prev = null; 
    // Last line 
    String last = null; 
    String line; 
    while ((line = br.readLine()) != null) { 
     prev = last; 
     last = line; 
    } 
    // Pattern used to extract the integers 
    Pattern pattern = Pattern.compile("\\d+"); 
    // Matcher for the previous line 
    Matcher matcher1 = pattern.matcher(prev); 
    // Matcher for the last line 
    Matcher matcher2 = pattern.matcher(last); 
    // Iterate as long as we have a match in both lines 
    while (matcher1.find() && matcher2.find()) { 
     // Value of previous line 
     int val1 = Integer.valueOf(matcher1.group()); 
     // Value of last line 
     int val2 = Integer.valueOf(matcher2.group()); 
     // Do something here 
    } 
} 

注:此假設我們有相同數量的兩行的整數,否則,你就可以比較不相關的值。


的情況下,另一種方法使用的Java 8,你可以使用非整數作爲分隔符,然後依靠splitAsStream(CharSequence input)所有的整數提取作爲List

... 
// Non integers as a separators 
Pattern pattern = Pattern.compile("\\D+"); 
// List of extracted integers in previous line 
List<Integer> previous = pattern.splitAsStream(prev) 
    .filter(s -> !s.isEmpty()) 
    .map(Integer::valueOf) 
    .collect(Collectors.toList()); 
// List of extracted integers in last line 
List<Integer> current = pattern.splitAsStream(last) 
    .filter(s -> !s.isEmpty()) 
    .map(Integer::valueOf) 
    .collect(Collectors.toList()); 
// Do something here 
0
  1. 需要對插入/提取代碼更清楚一點,它是由相同的進程/線程完成的。如果答案是肯定的,我會將請求的數據存儲在一個變量中,這樣可以節省一些訪問文件和操作數據的時間。

  2. 如果插入由另一個進程/線程完成,您應該小心,因爲存在讀/寫比賽。