使用contains方法查找包含字符串的行

时间:2019-07-16 11:32:18

标签: java

我有两个文件:

一个是CSV文件,其中包含以下内容:

Class
weka.core.Memory
com.google.common.base.Objects
client.network.ForwardingObserver

第二个是包含以下内容的txt文件:

1_tullibee  com.ib.client.ExecutionFilter
107_weka    weka.core.Memory
101_netweaver   com.sap.managementconsole.soap.axis.sapcontrol.HeapInfo
107_weka    weka.classifiers.Evaluation
guava   com.google.common.base.Objects
57_hft-bomberman    client.network.ForwardingObserver
18_jsecurity    org.jsecurity.web.DefaultWebSecurityManager

我想在txt文件中检索包含CSV文件中的类的行。为此:

try (BufferedReader br = new BufferedReader(new FileReader("/home/nasser/Desktop/Link to Software Testing/Experiments/running_scripts/exp_23/run3/CSV/MissingClasses_RW_No_Reduction.csv"))) {
    String line;
    while ((line = br.readLine()) != null) {
        System.out.println("==>> " + line);

        Scanner scanner = new Scanner(new File("/home/nasser/Desktop/Link to Software Testing/Experiments/running_scripts/exp_23/selection (copy).txt"));

        while (scanner.hasNextLine()) {
            String currentLine = scanner.nextLine();

            if(currentLine.contains("**>> " + line)){
                System.out.println(currentLine);
            }else {
                System.out.println("not found");
            }
        }
    }
}

运行它时,我得到not found的所有类都在CSV中,这不是我期望的。我希望将打印以下行:

107_weka    weka.core.Memory
guava   com.google.common.base.Objects
57_hft-bomberman    client.network.ForwardingObserver

如何解决?

2 个答案:

答案 0 :(得分:1)

如果您不希望输出not found==>> *,只需删除相应的代码行

try (BufferedReader br = new BufferedReader(new FileReader("csv.txt"))) {
    String line;
    while ((line = br.readLine()) != null) {
        Scanner scanner = new Scanner(new File("copy.txt"));

        while (scanner.hasNextLine()) {
            String currentLine = scanner.nextLine();

            if (currentLine.contains(line)) {
                System.out.println(currentLine);
            }
        }

        scanner.close();  // added this, could use try-with but that is *advanced*
    }
}

这将完全按照要求生成以下输出:

107_weka    weka.core.Memory
guava   com.google.common.base.Objects
57_hft-bomberman    client.network.ForwardingObserver

位于我的文件夹中的明显使用过的文件...

答案 1 :(得分:1)

仅需两分钱:如果您使用的是Java 8,并且CSV文件相对较小,则只需执行以下操作:

List<String> csvLines = Files.lines(Paths.get(csvFilename))).collect(Collectors.toList());
Files.lines(Paths.get(txtFileName)))
 .filter(txtLine -> csvLines.stream().anyMatch(txtLine::contains))
 .forEach(System.out::println);