简体   繁体   English

无法从ProcessBuilder运行其他Java程序?

[英]Could not run another java programs from ProcessBuilder?

TestClass.java TestClass.java

package test;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class TestClass {
    public static void main(String[] args) throws IOException {
        System.out.println("inside");
        ProcessBuilder pb = new ProcessBuilder("java", "-cp", "", "test.OtherClass");
        Process p = pb.start();
        BufferedReader reader = new BufferedReader(new InputStreamReader(p.getErrorStream()));
        StringBuilder builder = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            builder.append(line);
            builder.append(System.getProperty("line.separator"));
        }
        String result = builder.toString();
        System.out.println(result);
    }
}

OtherClass.java OtherClass.java

package test;

public class OtherClass {
    public static void main(String ar[]) {
        System.out.println("Hello Amit!");
    }
}

I am trying to run OtherClass from TestClass, but I am not able to do it. 我正在尝试从TestClass运行OtherClass,但是我无法做到这一点。 Running TestClass just prints "inside". 运行TestClass只会打印“内部”。 I am not getting any exception and I am clueless right now. 我没有任何例外,我现在一无所知。 I am implementing ProcessBuilder for the first time. 我是第一次实现ProcessBuilder。

NOTE: I was able to run simple program using ProcessBuilder. 注意:我能够使用ProcessBuilder运行简单的程序。 Also Can you tell what is meaning of -cp ; 还可以告诉-cp是什么意思吗? I googled a lot but could not find its meaning. 我在Google上搜索了很多,但找不到它的含义。

EDIT: 编辑:

I have updated code and now I am getting 我已经更新了代码,现在我得到了

inside
Error: Could not find or load main class test.OtherClass

Thanks! 谢谢!

Its likely to be the classpath. 它可能是类路径。 Assuming you have a directory called test, Have you tried something like: 假设您有一个名为test的目录,是否尝试过类似的操作:

ProcessBuilder pb = new ProcessBuilder("java", "-cp", ".", "test.OtherClass");

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

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