4

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.

6
  • What about starting with some java tutorials? Commented Oct 17, 2016 at 12:06
  • Please reformulate. You want to output from a Java application to a distinct Windows CMD ? Commented Oct 17, 2016 at 12:07
  • yes sending the output to cmd@rbntd Commented Oct 17, 2016 at 12:10
  • Possible duplicate of How to execute cmd commands via Java Commented Oct 17, 2016 at 12:24
  • 1
    If 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. Commented Oct 17, 2016 at 12:36

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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 It has fortunately already been done ! stackoverflow.com/questions/1248510/convert-string-to-keyevents

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.