How do i read in a file with buffer reader but skip comments with java
<p>I wrote a program that reads a file with buffer reader and stores data in a String variable. How can i modify it to make it skip single and multi-line comments?</p>

<p>Here is my code:</p>

<pre><code>import java.util.*;
import java.io.*;

public class IfCounter 
{
    public static void main(String[] args) throws IOException
    {
        // parameter the TA will pass in
        String fileName = args[0];

        // variable to keep track of number of if's
        int ifCount = 0;

        // create a new BufferReader
        BufferedReader reader = new BufferedReader( new FileReader (fileName));
        String line  = null;
        StringBuilder stringBuilder = new StringBuilder();
        String ls = System.getProperty("line.separator");

        // read from the text file
        while (( line = reader.readLine()) != null) 
        {
            stringBuilder.append(line);
            stringBuilder.append(ls);
        }

        // create a new string with stringBuilder data
        String tempString = stringBuilder.toString();

        // create one last string to look for our valid if(s) in
        // with ALL whitespace removed
        String compareString = tempString.replaceAll("\\s","");

        // check for valid if(s)
        for (int i = 0; i &lt; compareString.length(); i++)
        {
            if (compareString.charAt(i) == ';' || compareString.charAt(i) == '}' || compareString.charAt(i) == '{') // added opening "{" for nested ifs :)
            {
                i++;

                if (compareString.charAt(i) == 'i')
                {
                    i++;

                    if (compareString.charAt(i) == 'f')
                    {
                        i++;

                        if (compareString.charAt(i) == '(')
                            ifCount++;
                    } // end if
                } // end if
            } // end if

        } // end for

        // print the number of valid "if(s) with a new line after"
        System.out.println(ifCount + "\n");

    } // end main
} // end class
</code></pre>
