I am looking for a way to compare a string (which in this case will be a line from a text file) to every element in an array and see if there is a match. At a high level overview, I have a string array (about 100 elements) full of strings that are all contained somewhere in the file that need to be deleted. So I am reading a file into a StringBuffer and writing each line, except skipping over all lines that match an element in the array. This is what I have so far:
//Main Class calling the method
public class TestApp {
public static void main(String[] args) {
CompareAndDelete.RemoveDuplicateLines("C:/somelocation", 2Darray);
}
}
public class CompareAndDelete {
static string Line_of_Text;
static StringBuffer localBuff = new StringBuffer();
static FileReader Buffer;
static BufferedReader User_File;
public static void RemoveDuplicateLines(String local, String[][] duplicates) throws IOException
{
//Converting 2D array to one-dimensional array
final String[] finalDups = new String[duplicates.length];
for(int i = 0; i < duplicates.length; i++)
{
finalDups[i] = duplicates[i][0]+" "+duplicates[i][1];
}
int count = 0;
User_File = new BufferedReader(Buffer);
Set<String> Values = new HashSet<String>(Arrays.asList(finalDups));
while((Line_of_Text = User_File.readLine()) != null){
if(!(Values.contains(Line_of_Text))){
localBuff.append(Line_of_Text+"\n");
}else{
count++;
}
}
System.out.println(count);
//Printing StringBuffer to file
BufferedWriter testOutFile = new BufferedWriter(new FileWriter("C:/test.txt"));
testOutFile.write(localBuff.toString());
testOutFile.flush();
testOutFile.close();
}
So I am unsure of the IF statment, I know that it does not work properly, it currently is only removing the first few elements in the new StringBuffer because those lines happen to be towards the end of the file, and it does not recheck every line for a match with each element. I know there has to be a better way to do this... Thanks in advance for any help/suggestions.
**Updated: with code above, it is now throwing the following error on this line:
while((Line_of_Text = User_File.readLine()) != null){
Error:
Exception in thread "main" java.io.IOException: Stream closed
at sun.nio.cs.StreamDecoder.ensureOpen(StreamDecoder.java:51)
at sun.nio.cs.StreamDecoder.read(StreamDecoder.java:204)
at java.io.InputStreamReader.read(InputStreamReader.java:188)
at java.io.BufferedReader.fill(BufferedReader.java:147)
at java.io.BufferedReader.readLine(BufferedReader.java:310)
at java.io.BufferedReader.readLine(BufferedReader.java:373)
at compare.CompareAndDelete.RemoveDuplicateLines(CompareAndDelete.java:48)
at mainPackage.TestApp.main(TestApp.java:326)