在另一个程序中运行Java程序会出错

时间:2015-12-02 14:34:21

标签: java

我想在我的程序中执行另一个Java程序。我参考了here。为了测试我已经粘贴了与接受的答案显示相同的代码。我已经通过了一个简单的HelloWorld程序。程序编译完美,但是给出了Main class not found错误。

这是我的代码: 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!");
}`

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

在CMD或IDE上编译和运行相同的程序可以提供完美的输出。

2 个答案:

答案 0 :(得分:1)

您想从HelloWorld类启动main吗?我想,在这种情况下你应该运行这样的程序:

java -cp 'D:\' HelloWorld

因此,您需要在类路径中指定ClassPath - 'D:\'和条目类名称 - HelloWorld。

答案 1 :(得分:-1)

为什么要努力做事?使用内联编译器API,然后在将类本身加载到根类加载器后,只需在新类上执行main()方法。

相关问题