Reputation: 1456
I have two files:
One is a CSV file that contains the following:
Class
weka.core.Memory
com.google.common.base.Objects
client.network.ForwardingObserver
Second is a txt file that contains the following:
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
I would like to retrieve the lines in the txt files that contain the classes in the CSV file. To do so:
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");
}
}
}
}
When I run it, I get not found
with all the classes in the CSV which is not the case I expect. I expect the following lines to be printed:
107_weka weka.core.Memory
guava com.google.common.base.Objects
57_hft-bomberman client.network.ForwardingObserver
How to solve that?
Upvotes: 0
Views: 112
Reputation: 421
Just my two cents: If you're using Java 8, and the CSV file is relatively small, you can simply do this:
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);
Upvotes: 1
Reputation: 29700
If you don't want the not found
and the ==>> *
output, just delete the corresponding lines of code
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*
}
}
this will generate the following output, exactly as requested:
107_weka weka.core.Memory guava com.google.common.base.Objects 57_hft-bomberman client.network.ForwardingObserver
obviously used files located in my folder...
Upvotes: 1