2017-08-17 12 views
0

嗨StackOverflow的人,读线是不相符的

我有这个问题在我的系统,在那里我有一个文本文件 线记录的发展,我正在使用BufferedReader拆分每行按管道检索(|)。我正在使用Quartz来每天运行这个文件的读取。当我测试它时,我每分钟都会设置一次石英工作,以便我可以在每分钟实际读取文件的情况下测试它。它通过使用它来检查文本文件中的所有行。

BufferedReader reader = new BufferedReader((newInputStreamReader(inputStream)); 
String line = null; 
int counter = 0; 
while((line = reader.readLine()) != null){ 
    counter++; 
} 
System.out.println(counter); 

但是,当我分裂String,检索4451记录的结果是不一致的。有时候,它只能检索1000+到2000+的记录,有时它会检索4451,但不一致。这是我的代码。

try { 
BufferedReader reader = new BufferedReader((newInputStreamReader(inputStream)); 
String line = null; 
int counter = 0; 
String[] splitLine = null; 
while((line = reader.readLine()) != null){ 
    splitLine = line.split("\\|"); // Splitting the line using '|' Delimiter 
    for(String temp : splitLine) { 
     System.out.println(temp); 
    } 
    counter++; 
} 
System.out.println(counter); 
} catch (IOException e) { 
    e.printStackTrace(); 
} 

是分裂字符串和readfile在同一时间迭代可能是原因?

编辑: 情况没有发生异常。它仅通过使用counter变量来打印长度。

我的预期输出是我想检索文本文件中每行的所有记录,并将每行的字符串拆分为pipecounter是检索的行数。

+1

也许你正在压制一个异常。显示你的完整try/catch块。并修复编译错误。 – shmosel

+0

嗨@shmosel,我没有尝试/赶上,并没有发生错误。 – msagala25

+0

必须在某处尝试/捕捉。您发布的代码没有任何问题。不要让我们乞求[mcve]。 – shmosel

回答

-1

不应使用管道分隔符只是"|"而不是"\\|"

试试你的代码更改为:

splitLine = line.split("|"); // Splitting the line using '|' Delimiter 
+0

不,'split()'接受一个正则表达式。 – shmosel

+0

@shadow你的答案显然是错误的。去检查这里:https://stackoverflow.com/questions/10796160/splitting-a-java-string-by-the-pipe-symbol-using-split – Tavo

0

我没有找到代码中的任何错误,但我写了工作完全正常的代码。这里是代码

import java.io.BufferedReader; 
import java.io.FileReader; 
import java.io.IOException; 

class Test { 
    public static void main(String[] args) { 
     FileReader inputStream = null; 
     BufferedReader reader = null; 
     try { 
      inputStream = new FileReader("Input.txt"); 
      reader = new BufferedReader(inputStream); 
      String line = null; 
      int counter = 0; 
      String[] splitLine = null; 
      while ((line = reader.readLine()) != null) { 
       splitLine = line.split("\\|"); 
       for (String temp : splitLine) { 
        System.out.println(temp); 
       } 
       counter++; 
      } 
      System.out.println(counter); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } finally { 
      try { 
       reader.close(); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
     } 
    } 
}