[英]Reading Line of String in Text File is Not Consistent
您好StackOverFlow人们,
我在System的开发中遇到了这个问题,我在一个文本文件中有4451行记录,我正在使用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();
}
是字符串拆分和同时读取文件迭代可能是原因吗?
编辑:情境中没有异常发生。 它仅使用counter
变量打印的长度。
我的预期输出是我要检索文本文件中每行的所有记录,并通过pipe
在每行中拆分字符串。 counter
是检索到的行数。
我没有在您的代码中发现任何错误,但是我编写的代码运行良好。 这是代码
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();
}
}
}
}
管道分隔符不应该只是"|"
而不是"\\\\|"
?
尝试将代码更改为:
splitLine = line.split("|"); // Splitting the line using '|' Delimiter
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.