0

I have a html file which I have to search line by line and look for a particular string and then take some actions accordingly. The problem is that the string is being matched to the entire line of the each line of the html file. So if there are some spaces before the actual string in a given line, the match turns out to be false, even though it should be positive.

package read_txt;

import java.io.*;
class FileRead 
{
public static void main(String args[])
{
  try{
    // Open the file that is the first 
    // command line parameter
    FileInputStream fstream = new FileInputStream("textfile.html");
    // Get the object of DataInputStream
    DataInputStream in = new DataInputStream(fstream);
    BufferedReader br = new BufferedReader(new InputStreamReader(in));
    String strLine;
    //Read File Line By Line
    while ((strLine = br.readLine()) != null)   {
        // Print the content on the console
        //String a = "media query";
        switch (strLine) {
        case "@media query" :
            System.out.println("media query found");
            System.out.println("html file responsive");
            break;
        //  default :
            //  System.out.println("html file unresponsive");
            //break;
        }
    }
    //Close the input stream
    in.close();
    }catch (Exception e){//Catch exception if any
        System.err.println("Error: " + e.getMessage());
    }
}
}

In my code above, I am searching for a String "media query". Now suppose this is the html file being searched :

enter image description here

The codes works fine for this html file, but now suppose we have this html file :

enter image description here

The string match does not work although a media query string is present, but if I change the matched string to " media query" instead of "media query", it works again. Any idea how can I ignore the blank spaced occurring before appearance of any text in a line?

Cù Đức Hiếu
  • 5,569
  • 4
  • 27
  • 35
Ankit Sahay
  • 41
  • 1
  • 8

2 Answers2

0

In this case, I would think that using "switch" is not the right way to go.

You might use

if (strLine.contains("media query"))

but that will fail if the line has "media query" (two spaces instead of one). So, you best bet might be to use a regular expression.

Jamie
  • 1,888
  • 1
  • 18
  • 21
  • Thank you :) Yes, the only problem is the initial blank spaces, the probability of spelling errors or two spaces in between 'media' and 'query' is very low – Ankit Sahay Nov 08 '16 at 16:50
0

You could use endsWith, e.g.

if (strLine.endsWith("media query")) { ...

In cases, where the searched string could be somewhere in the middle of line you could use indexOf, e.g.

if (strLine.indexOf("medial quera") >= 0) { ...
Thomas Philipp
  • 261
  • 1
  • 5