我想在 Java 中设置并回显 Windows 变量:
public static void main(String[] args) throws IOException
{
Runtime rt = Runtime.getRuntime();
String[] cmd = { "cmd.exe", "/c", "set HOSTNAME=%COMPUTERNAME% "
+ "&& echo %HOSTNAME%" };
Process proc = rt.exec(cmd);
BufferedReader stdInput = new BufferedReader(
new InputStreamReader(proc.getInputStream()));
BufferedReader stdError = new BufferedReader(
new InputStreamReader(proc.getErrorStream()));
System.out.println("Output:\n");
String s = null;
while ((s = stdInput.readLine()) != null)
{
System.out.println(s);
}
System.out.println("Error (if any):\n");
while ((s = stdError.readLine()) != null)
{
System.out.println(s);
}
}
我希望程序会打印出我的计算机主机名,否则我会将此值用于其他目的。但输出是这样的:
Output:
%HOSTNAME%
Error (if any):
如何获取在命令 set HOSTNAME=%COMPUTERNAME%
中设置的值
最佳答案
这与 Java 无关,因为这是 cmd 解析命令的方式。整个命令将立即被解析以进行变量扩展。在解析命令时,变量尚不可用,因此它将被批处理文件中的任何内容替换,或在命令行中保持原样
您需要使用delayed expansion并使用 !!
cmd.exe /V:ON /c set HOSTNAME=%COMPUTERNAME% && echo !HOSTNAME!
/V:ON
用于启用延迟扩展
CMD [/A | /U] [/Q] [/D] [/E:ON | /E:OFF] [/F:ON | /F:OFF] [/V:ON | /V:OFF]
[[/S] [/C | /K] string]
...
/V:ON Enable delayed environment variable expansion using ! as the
delimiter. For example, /V:ON would allow !var! to expand the
variable var at execution time. The var syntax expands variables
at input time, which is quite a different thing when inside of a FOR
loop.
在批处理文件中,可以通过 setlocal EnableDelayedExpansion
启用它
但是为此目的,只需 cmd.exe/V:ON/c echo %COMPUTERNAME%
就足够了。但这仍然不是有效的方法。 There are better ways to get hostname in Java
Map<String, String> env = System.getenv();
if (env.containsKey("COMPUTERNAME"))
return env.get("COMPUTERNAME");
或
InetAddress.getLocalHost().getHostName()
关于java - Windows - 在Java程序中使用set和echo,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45451042/