How can I unblock from a Java started process?

2020-05-07 05:08发布

When executing some command(let's say 'x') from cmd line, I get the following message: "....Press any key to continue . . .". So it waits for user input to unblock.

But when I execute the same command ('x') from java:

Process p = Runtime.getRuntime().exec(cmd, null, cmdDir);
// here it blocks and cannot use outputstream to write somnething
p.getOutputStream().write(..);

the code blocks...

I tried to write something into the process's output stream, but how can i do that sice the code never reaches that line ?

标签: java process
8条回答
太酷不给撩
2楼-- · 2020-05-07 05:33

So this is my workaround to this problem, inspired from Alnitak's suggestion: Run the command like this:

Process p = Runtime.getRuntime().exec(cmd + " < c:\\someTextFile.txt", null, cmdDir);
...
int errCode = p.waitFor();
...

the 'someTextFile.txt' can be programatically created into the temporary dir then deleted.

查看更多
Explosion°爆炸
3楼-- · 2020-05-07 05:35

I had the same problem and I found a solution. It ins´t the most elegant, but it works.

1 - when you execute the process, you get the inputStream from the process 2 - Then you make a loop receiving the message shown in the prompt, if there was one 3 - When you see that you got from "prompt" the "press a key to continue", or whatever, you end the proccess

            // Creates the runtime and calls the command
        Process proc = Runtime.getRuntime().exec(Destino);

        // Get the proccess inputStream
        InputStream ips = proc.getInputStream();
        String output = "";

        int c = 0;

        // Read the output of the pro
        while ((c = ips.read()) != -1
                && !output.contains("Press any key to continue")) {
            output = output + (char)c;
        }

        // Destroy the proccess when you get the desired message
        proc.destroy();
查看更多
登录 后发表回答