You are here:

Java/Programmatically enter input into cmd

Advertisement


Question
I am using Java to call an external program which is command-based. That external program I'm using runs through the command prompt and at one point of time it will open up a second window which will then prompt the user for an input which is either 'y' or 'n'. How do I program using java codes such that the value 'y' or 'n' is automatically entered when prompted so that the users do not have to enter it themselves?

I have done a lot of research but none of them seems to work, such as println or OutputStream. One of them mentioned about using pipe;

e.g. echo y | external.exe

If this is the solution, where should I put it? Is it under the batch file I created to call the program or after the

Runtime rt = Runtime.getRuntime();
Process p = rt.exec("cmd /c start external.bat");

When I run the program, the first command prompt window shows C:\...\external.bat while the second window that pops up after the UAC prompt shows C:\...\external.exe which is to run that application.

Therefore, I want to auto-input the 'y' or 'n' in the second window.

Answer
If the program is opening a second window, and doesn't have any commandline options to automatically continue, there isn't any good solutions.

You could use the Robot class to manually type in the 'y' followed by enter, but this would be really clunky, as you wouldn't know when to do it, and any user intervention would cause issues. For example, if the user clicks to another application, you will end up typing 'y' into that application instead. If your planning to keep this "in-house" it might be fine to do something like this, but using this and releasing it to the end user can easily cause issues, as different computers may act differently and this approach can easily fail.

Java

All Answers


Answers by Expert:


Ask Experts

Volunteer


Artemus Harper

Expertise

I have a Masters in computer science. I can answer questions on core J2SE, swing and graphics. Please no questions about JSP or J2ME.

Experience

I have experience in Core Java, good background in Java swing/gui, some experience with JNI, Java reflection. Some experience in bio-informatics. Basics in c++ and c#

Organizations
Washington State University

Education/Credentials
MS in Computer Science from Washington State University and a BS in Mathematics and Computer Science from Central Washington University.

©2016 About.com. All rights reserved.