【问题标题】:Reading Line of String in Text File is Not Consistent读取文本文件中的字符串行不一致
【发布时间】:2017-08-17 02:15:54
【问题描述】:

大家好,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();
}

String 的拆分和 readfile 的迭代是否同时是原因?

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

我的预期输出是我想检索文本文件中每行的所有记录,并将每行的字符串按pipe 分割。counter 是检索到的行数。 p>

【问题讨论】:

  • 也许您正在抑制异常。展示你完整的 try/catch 块。并修复编译错误。
  • 嗨@shmosel,我没有try/catch,也没有发生错误。
  • 某处一定有try/catch。您发布的代码没有任何问题。不要让我们乞求minimal reproducible example
  • 你想计算 还是你想计算tokens?请告诉我们您得到什么结果,以及您期望的结果。 具体
  • 你的代码看起来足够合理,我们来谈谈这个不一致;您在阅读时正在写入此文件吗?

标签: java string split quartz-scheduler bufferedreader


【解决方案1】:

我在您的代码中没有发现任何错误,但我编写的代码运行良好。这是代码

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();
            }
        }
    }
}

【讨论】:

    【解决方案2】:

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

    尝试将您的代码更改为:

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

    【讨论】:

    猜你喜欢
    • 2016-09-09
    • 2016-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多