Run java.exe through ProcessBuilder leads to application hanging?

不羁岁月 提交于 2019-12-24 07:16:39

问题


I have the following code:

    ProcessBuilder pb = new ProcessBuilder("C:\\Program Files\\Java\\jdk1.8.0_111\\bin\\java", "-cp", "project_folder\\target\\classes", "package.ExternalProcess"); 
    Process p = pb.start();
    OutputStream processOutputStream = p.getOutputStream();
    IOUtils.write("1" + System.lineSeparator(), processOutputStream);
    InputStream processInputStream = p.getInputStream();
    System.out.println("--1--");
    System.out.println(process.isAlive()); // outputs true
    String result = IOUtils.toString(processInputStream, "UTF-8"); //<-- hangs here
    System.out.println("--2--");
    p.waitFor();
    System.out.println(result);

ExternalProcess source:

public class ExternalProcess {
    public static void main(String[] args) {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String input = null;
        try {
            input = br.readLine();
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("processed[" + input + "]");
    }
}

The first code produces
--1-- true

and hangs on

How to correct program and why does it hangs on?

P.S.

When I just try to write

java -cp project_folder\target\classes package.ExternalProcess

from cmd it waiting when I write something to the console and returns expected result

来源:https://stackoverflow.com/questions/43050217/run-java-exe-through-processbuilder-leads-to-application-hanging

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!