Try using this code:
//imports
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.List;
//create the array lists to save the data
private static List<String> readData = new ArrayList<String>();
private static List<String> readTerms = new ArrayList<String>();
private static List<String> splitData = new ArrayList<String>();
private static List<String> finalData = new ArrayList<String>();
public static void main(String[] args) throws Exception{
readData();
processData();
writeFinalData();
}
public static void readData() throws Exception{
//create readers
BufferedReader data = new BufferedReader(new FileReader(new File("Test.csv")));
BufferedReader term = new BufferedReader(new FileReader(new File("Terms.txt")));
//read the data and save it into the array lists
String line;
while((line = term.readLine()) != null){
readTerms.add(line);
}
while((line = data.readLine()) != null){
readData.add(line);
}
//close the readers
data.close();
term.close();
}
Now we have two array lists witch hold the data from the .csv file and the data from the terms file. The next step is to process this data and write it to a file.
public static void processData(){
//looping through every line in the .csv file, spliting it by , and saving every piece of the data into a new array list
for(String d : readData){
String[] split = d.split(",");
for(int i = 0; i < split.length; i++){
splitData.add(split[i]);
}
}
//searching the .csv file for keywords
for(String s : splitData){
for(String k : readTerms){
//testing if the data from the .csv file contains (or is equal to) the keyword. If true then we add it to the array list which holds the final data that will be writen back to the file
if(s.contains(k)){
finalData.add(s);
}
}
}
}
The last thing left to do is to write the data that matches the keywords back to a file.
public static void writeFinalData() throws Exception{
BufferedWriter bw = new BufferedWriter(new FileWriter(new File("words.txt")));
for(String s : finalData){
bw.write(s);
bw.newLine();
}
bw.close();
}