2016-11-21 32 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. 如果插入由另一个进程/线程完成,您应该小心,因为存在读/写比赛。

相关问题