简体   繁体   English

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

[英]Running Java Program in another Program gives error

I want to execute another Java program in my program. 我想在程序中执行另一个Java程序。 I have taken reference from here . 我从这里参考 For testing I have pasted same code as accepted answer shows.I have passed a simple HelloWorld program. 为了测试,我粘贴了与接受的答案所示相同的代码。我通过了一个简单的HelloWorld程序。 Program compiles perfectly but gives Main class not found error. 程序可以完美编译,但会给Main class未找到错误。

Here is my code: Server.java 这是我的代码: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: 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 输出: 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. 在CMD或IDE上编译并运行同一程序可提供完美的输出。

You want to start main from HelloWorld class? 要启动main从HelloWorld类? 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. 因此,您需要指定ClassPath-'D:\\',并从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. 使用内联编译器API,然后在将类本身加载到根类加载器后,只需对新类执行main()方法即可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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