2

我需要(编译和)在 Java 中使用 main 方法运行另一个类并读取它的输出,然后写入它的输入,但首先要专注于阅读。假设我需要测试应用程序是否在标准输出上写入“123”,这是我的想象:

public class TestMe {
    public static void main(String[] args) {
        System.out.println("123");
    }
}

...

public class Tester {

    public static void main(String[] args) {
        Runtime runtime = Runtime.getRuntime();
        try {
            Process exec = runtime.exec("java works.TestMe");
            BufferedReader br = new BufferedReader(new InputStreamReader(exec.getInputStream()));
            if (br.readLine().equals("123")) {
                System.out.println("Your program is working fine");
            } else {
                System.out.println("Yout program is bad and you should feel bad");
            }
        } catch (IOException ex) {

        }

    }
}

我使用 exec() 方法加载了运行时类创建的进程,但读取器没有读取任何数据并抛出空指针异常(在方法 readLine() 上)。我在不同的包中都有两个类,并且我正在使用 netbeans,如果它无论如何重要的话。任何帮助。

4

0 回答 0