2

I want to use variables in CMD via Java runtime. What I have tried is this:

Runtime runtime = Runtime.getRuntime();
        try {
            runtime.exec("cmd /c start cmd.exe /K \"ping localhost &&" +
                                                   "set /p userInput=Do you want to exit? [y/n] &&" +
                                                   "echo %userInput%\"");
        } catch (IOException ex) {
        }

But instead of giving the value of variable userInput it displays the variable name as it is with % symbol on both sides:

Pinging Desktop-PC [::1] with 32 bytes of data:
Reply from ::1: time<1ms
Reply from ::1: time<1ms
Reply from ::1: time=1ms
Reply from ::1: time=1ms

Ping statistics for ::1:
    Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
    Minimum = 0ms, Maximum = 1ms, Average = 0ms
Do you want to exit? [y/n] y
%userInput%

whereas if I run the same command from CMD it gives me the value of variable

D:\>set /p userInput=Do you want to exit? [y/n]
Do you want to exit? [y/n] y

D:\>echo %userInput%
y
3
  • Consider using ProcessBuilder instead of Runtime, it gives you more flexibility and more readability executing your command Commented Feb 7, 2019 at 19:36
  • Also why don't you use a Scanner to capture user input? You can just run your process, output the result to System.out and ask the user if he wants to run the process again. Commented Feb 7, 2019 at 19:40
  • Try runtime.exec("cmd /c start cmd.exe /V /K \"ping localhost &&" + and "echo !userInput!\"");. Is this working now? Commented Feb 7, 2019 at 19:49

1 Answer 1

2

You will need delayed expansion which is enabled in cmd with the /V option. Therefore, you should use:

Runtime runtime = Runtime.getRuntime();
        try {
            runtime.exec("cmd /c start cmd.exe /V /k \"ping localhost &&" +
                                                   "set /p userInput=Do you want to exit? [y/n] &&" +
                                                   "echo !userInput!\"");
        } catch (IOException ex) {
        }

which should work for you.

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

Comments

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.