vishesh
vishesh

Reputation: 2045

parse java string in java

I want to parse java code using java.

problem is , when I pass the java code to parse method,it does not take it as string.How do I escape the code to be parsed

public class JavaParser {

    private int noOfLines;

    public void parse(String javaCode){
        String[] lines = javaCode.split("[\r\n]+");
        for(String line : lines)
            System.out.println(line);
    }



     public static void main(){
            JavaParser a = new JavaParser();
            a.parse("java code;");
     }
}

Upvotes: 1

Views: 411

Answers (2)

CloudyMarble
CloudyMarble

Reputation: 37566

You need to read the java code file as a text file, line by line or alla t once for example:

FileInputStream inputStream = new FileInputStream("foo.java");
try {
    String everything = IOUtils.toString(inputStream);
} finally {
    inputStream.close();
}

Then you can parse the everything string.

Upvotes: 2

Mark Bramnik
Mark Bramnik

Reputation: 42431

maybe you can describe what you're trying to achieve?

In general its java's compiler (like javac) work to parse the java source files.

Quick googling revealed this project that can suit your needs

As of java 6 you can invoke compiler as a part of your code (java exposes the compiler API). This can be helpful if you're trying to compile the code after you read it. In general you can read this article, maybe you'll find it helpful

Hope this helps

Upvotes: 0

Related Questions