【问题标题】:How to check if multiple conditions strings exist in the csv using BufferedReader?如何使用BufferedReader检查csv中是否存在多个条件字符串?
【发布时间】:2021-03-08 04:48:58
【问题描述】:

我正在使用BufferedReader 检查多个字符串是否存在于一个文件中,并且我正在使用以下脚本:

int n = 41; // The line number
String line;
BufferedReader br = new BufferedReader(new FileReader(context.tfilelistdir)); 
for (int i = 0; i < n; i++)
{
    line = br.readLine();
    if (line.contains("$$WORDS$$ ABC") && line.contains("$$WORDS$$ XYZ"))
    {
        do something
    }
}

这里我需要检查字符串 $$WORDS$$ ABC $$WORDS$$ XYZ 是否都存在于 csv 文件中的不同行/列中。 BufferedReader 的行不接受&amp;&amp;。它仅适用于|| (OR) 条件 BufferedReader 在不断读取记录时会覆盖条目。

有什么方法可以检查 CSV 文件中是否存在两个条件(字符串存在)?

【问题讨论】:

    标签: java csv bufferedreader equals contains


    【解决方案1】:

    如果子字符串在不同行中,则需要引入一些布尔标志来跟踪每个特定条件。

    另外,最好使用try-with-resources确保文件/阅读器资源正确关闭,并检查在阅读过程中是否没有到达文件结尾(然后br.readLine()返回null)。

    int n = 41; // The line number
    String line;
    try (BufferedReader br = new BufferedReader(new FileReader(context.tfilelistdir))) {
        boolean foundABC = false;
        boolean foundXYZ = false;
        int i = 0;
        while ((line = br.readLine()) != null && i++ < n) { // read at most n lines
    
            foundABC |= line.contains("$$WORDS$$ ABC"); // will be true as soon as ABC detected
            foundXYZ |= line.contains("$$WORDS$$ XYZ"); // will be true as soon as XYZ detected
            if (foundABC && foundXYZ) { // not necessarily in the same line
                //do something
            }
        }
    }
    

    【讨论】:

    • 感谢您的解决方案,它的完美 - 非常感谢它。我有一个小调整,因为我只想打印匹配的行而不打印 if 循环内的所有内容- 我该怎么做,因为我正在使用它打印所有带有输出的行,例如 if (foundABC && foundXYZ) { System.out.println("MATCH 1 FOUND"); //System.out.println(line); }
    • 案例 2:我还需要使用 if 循环检查不同的条件,比如不同的其他行是否有不同的条件匹配,所以我写成这样:foundABC |= line.startsWith ("$$WORDS$$ 9"); foundXYZ |= line.contains("COND=Test"); else if (foundABC && foundXYZ) { System.out.println("MATCH 2 FOUND"); //System.out.println(line);同样,我需要根据布尔标志检查各种条件/匹配项,它必须进入该 if 嵌套循环并仅打印具有匹配项的特定行代码是否准确?
    • 1.您可以在找到两种模式后立即重置标志,或者在循环中添加标志并检查当前行的条件是否为真:boolean currFoundABC = line.contains("$$WORDS$$ ABC"); boolean currFoundXYZ = line.contains("$$WORDS$$ XYZ"); foundABC |= currFoundABC; foundXYZ |= currFoundXYZ; if (foundABC &amp;&amp; foundXYZ &amp;&amp; (currFoundABC || currFoundXYZ)) {/* match found */}
    • 可能最后一件事需要使用正则表达式搜索模式,但这对于 cmets 中的问题来说似乎有点太多了 :) 此外,对于案例 2,需要进行额外的说明,并且尤其是输入数据、预期输出和实际输出。如果您有新问题,请不要犹豫在 SO 上发布新问题,并且不要忘记接受/投票有用的答案。
    • 感谢 alex 感谢您的帮助,我创建了一个单独的线程来从字段中提取值,因为这里我们刚刚讨论了 if 条件来检查值是否仅存在。请在您获得有机会分享您的反馈stackoverflow.com/questions/65033185/…
    猜你喜欢
    • 2022-01-08
    • 1970-01-01
    • 2011-03-24
    • 1970-01-01
    • 1970-01-01
    • 2013-08-20
    • 2021-10-18
    • 1970-01-01
    • 2021-10-07
    相关资源
    最近更新 更多