Finding if conditions in .java file

2019-09-11 23:22发布

问题:

I tried to make method which will finding all if conditions in .java file (I assume that file contain only correct if instructions). It should count all "if", but not that which are sorrounded with comments or treaded as string. I tried to solve this problem with StringTokenizer, but I don't know how elided line after "//" sign and strings sorrounded with " ".Is it possible to realize this problem in this way, at all?

public int getIfCount()
{
    int counter = 0;
    String t = "";

    try 
    {
        FileReader file = new FileReader(path);

        StringBuffer sb = new StringBuffer();

        int tmp;

        while ((tmp = file.read()) != -1)
        {
            sb.append((char)tmp);
        }

        t = sb.toString();

        StringTokenizer stk = new StringTokenizer(t);

        String token;


        while (stk.hasMoreTokens())
        {
            token = stk.nextToken();

             if (token.contains("/*"))
            {
                while (stk.hasMoreTokens())
                {
                    if (stk.nextToken().contains("*/"))
                        break;
                }
            }
            else if (token.contains("//"))
            {
                while (stk.hasMoreTokens() && stk.nextToken() != "\n")
                {
                    if (stk.nextToken().endsWith("\n"))
                        break;
                }
            }
            else if (token.contains("\""))
            {
                if (!token.endsWith("\""))
                    while (stk.hasMoreTokens())
                    {
                        if(stk.nextToken().contains("\""))
                            break;
                    }
            }
            else if (token.startsWith("if"))
                counter++;
        }
    } 

    catch (FileNotFoundException e) 
    {
        System.out.println("This file does not exist!");
    } 
    catch (IOException e) 
    {
        System.out.println("ERROR");
    }

    return counter;
}

回答1:

No need to implement it yourself. What you are doing is implementing the basics of a parser. Although it is good to have some idea of what is going on when parsing, I suggest using a library such as https://github.com/javaparser/javaparser. Have fun.