简体   繁体   中英

Running Java Program in another Program gives error

I want to execute another Java program in my program. I have taken reference from here . For testing I have pasted same code as accepted answer shows.I have passed a simple HelloWorld program. Program compiles perfectly but gives Main class not found error.

Here is my code: Server.java

public static void main(String args[]) {
    try {
        runProcess("javac D:\\HelloWorld.java");
        runProcess("java D:\\HelloWorld");
    } catch (Exception e) {
        e.printStackTrace();
    }
}

private static void printLines(String name, InputStream ins) throws Exception {
    String line = null;
    BufferedReader in = new BufferedReader(
            new InputStreamReader(ins));
    while ((line = in.readLine()) != null) {
        System.out.println(name + " " + line);
    }
}

private static void runProcess(String command) throws Exception {
    Process pro = Runtime.getRuntime().exec(command);
    printLines(command + " stdout:", pro.getInputStream());
    printLines(command + " stderr:", pro.getErrorStream());
    pro.waitFor();
    System.out.println(command + " exitValue() " + pro.exitValue());
}

HelloWorld.java:

`public static void main(String args[]){
    System.out.println("Hello World!");
}`

Output: exitValue() 0 for javac stderr: Error: Could not find or load main class D:\\HelloWorld exitValue() 1 for java

Compiling and running same program on CMD or IDE gives perfect output.

You want to start main from HelloWorld class? I think, in that case you should run program something like this:

java -cp 'D:\' HelloWorld

So, you need to specify ClassPath - 'D:\\' and entry class name from classpath - HelloWorld.

Why try to do things the hard way? Use the inline compiler API and then simply execute the main() method on your new class after loading the class itself into your root classloader.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM