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.
Asked
Active
Viewed 1,634 times
4

Coded9
- 159
- 2
- 14
-
What about starting with some java tutorials? – abbath Oct 17 '16 at 12:06
-
Please reformulate. You want to output from a Java application to a distinct Windows CMD ? – rbntd Oct 17 '16 at 12:07
-
yes sending the output to cmd@rbntd – Coded9 Oct 17 '16 at 12:10
-
Possible duplicate of [How to execute cmd commands via Java](http://stackoverflow.com/questions/4157303/how-to-execute-cmd-commands-via-java) – xenteros Oct 17 '16 at 12:24
-
@xenteros .. Suppose I would like to display Hello on cmd,how to do that ? – Coded9 Oct 17 '16 at 12:28
-
1If I'm not mistaken, the problem is that to display a `cmd` CLI, you have to call `cmd /C start`, where you call `cmd` (actually `conhost`?) 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 first `cmd` process, which has no interface. – Aaron Oct 17 '16 at 12:36
1 Answers
4
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.
-
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) – Aaron Oct 17 '16 at 12:53
-
1@Aaron It has fortunately already been done ! http://stackoverflow.com/questions/1248510/convert-string-to-keyevents – rbntd Oct 17 '16 at 13:03