0

I'm trying to locate the beginning of a string in a txt file using a Java program which I will then have to delete from the txt file. The problem is that it doesn't recognize the string I want to search and delete.

This is the example of the txt file:

enter image description here

I want to locate the string "(GmmiVariables)" and subsequently delete it from the file. I wrote this code:

 public static void main(String[] args) throws IOException {
    BufferedReader b = new BufferedReader(new FileReader("QD48.txt"));
     String s="";

     while((s=b.readLine()) != null) {
     if(s.contains("(GmmiVariables)"))
        System.out.println(s);
        s=b.readLine();
   }
 }

It doesn't print anything to me even if the string is present in the file and I can't understand why. Will it be due to the fact that txt files have spaces between each string?

Roberto
  • 29
  • 4

1 Answers1

0

Why are you reading the line twice?

while((s=b.readLine())/* read first time */ != null) {
    if(s.contains("(GmmiVariables)"))
       System.out.println(s);
       s=b.readLine();/* read second time */
}

remove the second b.readLine(), you miss alternate lines in your text file. GmmiVariables is on the 10th line. Change your while loop to look something like this and check if that works->

while((s=b.readLine()) != null) {
    if(s.contains("(GmmiVariables)"))
       System.out.println(s);
}