如何通过Java使用CMD变量

时间:2019-02-07 19:34:34

标签: java cmd

我想通过Java运行时在CMD中使用变量。 我尝试过的是这个

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) {
        }

但是,不给出变量“ userInput”的值,而是按原样显示变量名称,并在其两侧都带有“%”符号

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%

如果我从CMD运行相同的命令,它将为我提供变量的值

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

D:\>echo %userInput%
y

1 个答案:

答案 0 :(得分:2)

您将需要delayed expansion,该How to check Wi-Fi connection (SSID) when connected to MOBILE at the same time on Android {{3}}在cmd中通过/V选项启用。使用:

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) {
        }

应该为您工作的