1

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;");
     }
}
1
  • Can you show the input and output of your program run? (when you don't get expected output) Commented Sep 13, 2012 at 5:49

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.