原因是您在 64 位 Windows 上运行 32 位 Java VM。在这种情况下,%SystemRoot%\syswow64\cmd.exe 将被执行,而不是 %SystemRoot%\system32\cmd.exe。
小例子
public static void main(String[] args) throws Exception {
for (String s : Arrays.asList("java.vm.name", "sun.arch.data.model")) {
System.out.printf("%s=%s%n", s, System.getProperty(s));
}
ProcessBuilder pb = new ProcessBuilder("cmd.exe", "/c", "query session");
pb.redirectOutput(ProcessBuilder.Redirect.INHERIT);
pb.redirectError(ProcessBuilder.Redirect.INHERIT);
pb.start();
}
在 64 位 Windows 上使用 32 位 JVM 输出
java.vm.name=Java HotSpot(TM) Client VM
sun.arch.data.model=32
'query' is not recognized as an internal or external command,
operable program or batch file.
在 64 位 Windows 上使用 64 位 JVM 输出
java.vm.name=Java HotSpot(TM) 64-Bit Server VM
sun.arch.data.model=64
SESSIONNAME USERNAME ID STATE TYPE DEVICE
services 0 Disc
>console ..... 1 Active
编辑
%SystemRoot%\syswow64\cmd.exe 不知道查询命令。
C:\Windows\SysWOW64>cmd
Microsoft Windows [Version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation. All rights reserved.
C:\Windows\SysWOW64>query
'query' is not recognized as an internal or external command,
operable program or batch file.
%SystemRoot%\system32\cmd.exe知道查询命令。
C:\Windows\System32>cmd
Microsoft Windows [Version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation. All rights reserved.
C:\Windows\System32>query
Invalid parameter(s)
QUERY { PROCESS | SESSION | TERMSERVER | USER }