With Java, run multiple commands in the same cmd.exe window

后端 未结 3 885
名媛妹妹
名媛妹妹 2020-12-10 20:39

I\'m developing a Java application that will be run on a Windows computer occasionally. At some point I need to run a Cygwin prompt and performs some commands in it.

3条回答
  •  不思量自难忘°
    2020-12-10 21:27

    If you do not need to show a console on the screen, that is easy. You have some simple steps to follow :

    • start a Process via `Process cmd = new ProcessBuilder("cmd.exe").start();
    • send your commands to cmd.getOutputStream()
    • read the result of the commands from cmd.getInputStream() and/or cmd.getErrorStream()
    • when finished with it close cmd.getOutputStream(), and if necessary kill the process by cmd.destroy()

    Optionnaly, you can have output and error stream to be merged :

    Process cmd = new ProcessBuilder("cmd.exe").redirectErrorStream(true).start();
    

    then you simply ignore cmd.getErrorStream() and only read from cmd.getInputStream()

提交回复
热议问题