3

I need to compile an external java file (say a.java). This is the code i wrote for the same.

(String path contains the path to the java and class file)

    command[0] = "javac";
    command[1] = path+"a.java";
    p = Runtime.getRuntime().exec(command);        

The above code seems to work just fine. But the below code

    command[0] = "java";
    command[1] = "a";
    command[2] = "-cp";
    command[3] = "."+path+"a";
    p = Runtime.getRuntime().exec(command);        
    stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
    stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));
    while ((temp = stdInput.readLine()) != null) result += "\n" + temp;
    while ((temp = stdError.readLine()) != null) result += "\n" + temp;

Causes the following error

java.lang.NoClassDefFoundError: a
Exception in thread "main" 

Could someone explaine the problem with this code. Thanks !

1 Answer 1

4

You're specifying the class name first, and then the arguments for the classpath. The class name is always the last thing to come before the program-specific arguments. In your case, the classpath part will therefore not be treated as an option - it'll be considered as two arguments (-cp and the path) to the Java program itself.

So instead of:

java a -cp (whatever)

you want

java -cp (whatever) a
Sign up to request clarification or add additional context in comments.

6 Comments

I tried - command[0] = "java"; command[1] = "-cp"; command[2] = "."+path+"\\temp\\"; command[3] = "a"; But i'm still getting the same error. Is this command correct ?
@randomuser: Try running it from the command line first - it'll be a lot easier to experiment that way. Is the class file in the temp directory?
I get the same error when i run it using cmd, I found someone with same problem It seems a similar command worked for him.
@randomuser: That problem was due to putting the class filename rather than the class name. That's not your problem - I suspect your problem is that you're not compiling into the temp directory.
When working with cmd, when i change the current directory to the directory containing the .java file and the .class file, java a works just fine though. But when i explicitly try to avoid changing the current directory and try something like this java c:\\path_to_dir\\a I get the same error mentioned earlier.
|

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.