Run an interactive command using apache commons exec

I want to run an interactive command with apache commons exec. Everything works, except that when my command is executed and waiting for user input, I do not see my input in the console until I press the enter key, which makes it unusable.

This is an example of an interactive program:

public static void main(String[] args) {
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        String line = null;
        while (true) {
            System.out.print("=> ");
            try {
                line = in.readLine();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            System.out.println(line);
        }
    }

Now I want to accomplish this using apache commons exec as follows:

public static void main(String[] args) {
    Executor ex = new DefaultExecutor();
    ex.setStreamHandler(new PumpStreamHandler(System.out, System.err, System.in));
    CommandLine cl = new CommandLine("java");
    cl.addArguments("-cp target\\classes foo.bar.Main");

    try {
        ex.execute(cl);
    } catch (ExecuteException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

As I said, it basically works, I get the "=>" prompt, but when I type something, I don’t see it until I press enter. I am doing this on Windows 7 with a cmd prompt. I would appreciate any hint on how to achieve the desired behavior.

: , , linux. , windows cmd. , , Windows.

Edit2: msys powershell, .

Edit3: , cmd. , , .

CommandLine cl = new CommandLine("cmd");
cl.addArguments("/C java -cp target\\classes foo.bar.Main");

+3
2

, ; , , ?

: " " "?", OutputStream , ExecuteStreamHandler, . - :

Executor ex = new DefaultExecutor();

// Create an output stream and set it as the process' input
OutputStream out = new ByteArrayOutputStream();
ex.getStreamHandler().setProcessInputStream(out);
...
try
{
    ex.execute(cl);
    out.write("\n".getBytes()); // TODO use appropriate charset explicitly
...
+2

Apache exec org.apache.commons.exec.DefaultExecuteResultHandler, non-blocking. , .

0

Source: https://habr.com/ru/post/1760143/


All Articles