0

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)
  • If you really want to do it this way, you should write a method that accomplished your task. Or, you could look into the prebuilt java collections classes, like ArrayList and Set and stuff to find one that does what you need – D. Ben Knoble Aug 07 '15 at 19:07
  • Doesn't append just add that empty space? Not sure how exactly it is deleting it. Won't it be better to set the value of that text to an empty string instead? – SomeStudent Aug 07 '15 at 19:10

2 Answers2

0

This can be accomplished quite efficiently by adding your String array members to a Set, and then checking whether the set contains() the current line. Example:

Set<String> ignoredStrings = new HashSet<String>(Arrays.asList(arr));

String line;
while ((line = file.readLine()) != null) {
    if (!ignoredStrings.contains(line)) {
        buffer.append(line);
        buffer.append("\n");
    }
}
jwueller
  • 30,582
  • 4
  • 66
  • 70
  • Downvoters, please explain yourselves. – jwueller Aug 07 '15 at 19:14
  • I have tried this pretty much identically to your suggestion but am getting the following error on the while statement line: 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) ..... – Bryan Christensen Aug 07 '15 at 19:47
  • @BryanChristensen: Without a [SSCCE](http://sscce.org/), it is very hard to find the cause of such an error. It seems to be related to loading the lines, not checking whether those are contained in an array, though. – jwueller Aug 07 '15 at 20:11
  • I have update the code in my question description and included the error as well – Bryan Christensen Aug 10 '15 at 14:18
  • Nevermind, I found my own error, I was missing where I actually assigned the variable Buffer to the file variable, local. You're solution worked perfectly, thanks for your help – Bryan Christensen Aug 10 '15 at 19:23
0

Here is a method:

public boolean isStringInArray(String str, String[] strarr){
    for(String s: strarr){
        if(str.equals(s)) return true;
    }
    return false
}

isStringInArray("Hello", new String[]{"Hello", "World"}); // True           
isStringInArray("Hello", new String[]{"hello", "World"}); // False