run interactive command line application from java

前端 未结 2 1743
逝去的感伤
逝去的感伤 2020-12-11 02:42

I normally use java.lang.ProcessBuilder and java.lang.Process to run external command line programs, and it works fine for run-and-done commands. For example, this would run

相关标签:
2条回答
  • 2020-12-11 03:29

    Redirecting stdin and stdout is certainly one option for simple command-line programs.

    Using a "robot" class is another, if you actually need to script keystrokes (for example, in a test script):

    • http://www.java-tips.org/java-se-tips/java.awt/how-to-use-robot-class-in-java.html

    • http://download.java.net/jdk7/archive/b123/docs/api/java/awt/Robot.html

    Writing a simple .bat file or shell script, that calls your Java program and uses "<" and ">" redirection operators is yet a third option.

    It all depends on exactly what you're looking for :)

    0 讨论(0)
  • 2020-12-11 03:33

    According to the documentation you should be able to redirect the input and output streams. This tells it to use the System.in/System.out from the parent process:

    builder.redirectInput(ProcessBuilder.Redirect.INHERIT);
    builder.redirectOutput(ProcessBuilder.Redirect.INHERIT);
    

    If you want to write things to the processes's input:

    If the source is Redirect.PIPE (the initial value), then the standard input of a subprocess can be written to using the output stream returned by Process.getOutputStream(). If the source is set to any other value, then Process.getOutputStream() will return a null output stream.

    0 讨论(0)
提交回复
热议问题