How to use CMD Variables via Java?

anant :

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
double-beep :

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.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=152267&siteId=1