我有一个运行以下代码的jar文件:

public class InputOutput {

    /**
     * @param args
     * @throws IOException
     */
    public static void main(String[] args) throws IOException {
        boolean cont = true;
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        while (cont) {
            System.out.print("Input something: ");
            String temp = in.readLine();
            if (temp.equals("end")) {
                cont = false;
                System.out.println("Terminated.");
            }
            else
                System.out.println(temp);
        }
    }
}


我想编程另一个执行该jar文件的Java类,并且可以获取输入并将输出发送给它。可能吗?我当前的代码是这样,但它不起作用:

public class JarTest {

    /**
     * Test input and output of jar files
     * @author Jack
     */
    public static void main(String[] args) {
        try {
            Process io = Runtime.getRuntime().exec("java -jar InputOutput.jar");
            BufferedReader in = new BufferedReader(new InputStreamReader(io.getInputStream()));
            OutputStreamWriter out = new OutputStreamWriter(io.getOutputStream());
            boolean cont = true;
            BufferedReader consolein = new BufferedReader(new InputStreamReader(System.in));
            while (cont) {
                String temp = consolein.readLine();
                out.write(temp);
                System.out.println(in.readLine());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}


谢谢你的帮助

最佳答案

使用Runtime.exec取决于平台。

如果您使用的是Windows,请尝试添加:

cmd /c




java -jar .... etc. et


就像是:

...getRuntime().exec("cmd /c java -jar InputOutput....


另请参见:Make system call and return stdout output.

10-08 06:20