Question

I was doing some cmd commands via java that are only input in the command prompt. I was wondering if there was a way to programatically fetch and reply to a command prompt question via Java?

e.g.: I add a remote GIT repository to my GIT structure locally, so when I execute:

$ git remote add [url],

I get prompted for a password. Can i catch this message (for example to pass the message to the user) AND reply in the same command prompt programming object/cmd window.

(the AND is explicitly in there because it would be useless to execute above command, read prompt reply, close command prompt, send password via a new cmd command in a new and thus non-related new prompt window).

Was it helpful?

Solution

If you are executing the command using Runtime.getRuntime().exec, capture/monitor the sub process's input stream and write to the output stream to send message to it.

E.g

    Process process = Runtime.getRuntime().exec("Command ");        
    OutputStream pout = process.getOutputStream();
    PrintWriter pw = new PrintWriter(pout);
    pw.println("Command response here");

OTHER TIPS

YOu can interact with the standard input / output / error streams of another command by using a ProcessBuilder to start that command as a Process. In that case, the process usually won't directly talk to a command window, so you'll have to print its output to the user if that is needed.

Note that some processes take particular care not to read passwords from standard input, but from the console window instead. In that case, the above might not work. Usually commands do provide some means to specify a different source for passwords. In the case of git, please search for the GIT_ASKPASS environment variable as well as the core.askpass configuration setting.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top