run class file as separate process from java code

2019-08-10 03:15发布

问题:

public static void main(String args[]) throws IOException
{
    Process p = Runtime.getRuntime().exec("java E:/workspace/JNIProgram/src/JNIProgram.class");
}   

so I have this code and am trying to run the JNIProgram.class file however the program gets terminated instantly without doing its job (which is to create a new txt file and write to it)

So what am I doing wrong

回答1:

The java command expects a Java class name, not a filename.

So the command java E:/workspace/JNIProgram/src/JNIProgram.class is wrong. If you try this manually from a command prompt window you'll get an error message.

The command should be something like this:

java -cp E:\workspace\JNIProgram\src JNIProgram

Note: What's after the -cp option is the classpath, and after that the fully-qualified class name (which is just JNIProgram, if the class is not in a package).

First make sure that you can run the command manually from the command line before you make it work from another Java program.