I am trying to open a command prompt from a java class and send output to the new command prompt.
I can open cmd using process. Gone through all the answers on SO,but couldn't figure out how can I pass the output to the just created cmd window.
1 Answer
This might not be practical or even usable, but it does the job :
String[] command = {"cmd", "/c", "start", "cmd.exe"};
try {
new ProcessBuilder(command).start();
Robot r = new Robot();
r.keyPress(KeyEvent.VK_SHIFT);
r.keyPress(KeyEvent.VK_H);
r.keyRelease(KeyEvent.VK_H);
r.keyRelease(KeyEvent.VK_SHIFT);
r.keyPress(KeyEvent.VK_E);
r.keyRelease(KeyEvent.VK_E);
r.keyPress(KeyEvent.VK_L);
r.keyRelease(KeyEvent.VK_L);
r.keyPress(KeyEvent.VK_L);
r.keyRelease(KeyEvent.VK_L);
r.keyPress(KeyEvent.VK_O);
r.keyRelease(KeyEvent.VK_O);
} catch (IOException | AWTException e) {
e.printStackTrace();
}
This opens a CMD and write (a bit too literally maybe) "Hello" in the CMD.
See this answer if you want to type a String.
2 Comments
Aaron
God, this is awful... Here pour soul, take my upvote for having had to consider this possibility ! (On a more serious tone, if no better solution is found one should obviously create a function to translate a
String to a list of keystrokes)rbntd
@Aaron It has fortunately already been done ! stackoverflow.com/questions/1248510/convert-string-to-keyevents
cmdCLI, you have to callcmd /C start, where you callcmd(actuallyconhost?) and ask it to start another instance with a CLI. If you try to write to the process' OS, you're actually writing to the firstcmdprocess, which has no interface.