简体   繁体   中英

Windows - Using set and echo in Java program

I want to set and echo a Windows variable in Java:

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

I expect the program will print out my computer host name or I will use this value for another purpose. But the output is just like this:

Output:

%HOSTNAME%
Error (if any):

How could I get the value that I have set in the command set HOSTNAME=%COMPUTERNAME%

Your syntax for running two commands at once is wrong. Try using a single & in the command line instead of && .

The real problem, I think, is that cmd.exe does all variable substitution before executing the command line (including parsing the && ). When it finds the syntax %HOSTNAME% for a variable that doesn't exist (yet), it leaves the text as is: %HOSTNAME% . So try issuing two commands to the same process, followed by an exit command.

Another approach is to change the command to:

set HOSTNAME=%COMPUTERNAME% & SET HOSTNAME

Then you will get back the string "HOSTNAME=my_computer_name" , from which you can strip out the leading "HOSTNAME=" prefix.

It's irrelevant to Java because it's how cmd parses the command. The whole command will be parsed at once for variable expansion. At the time the command is parsed the variable is not yet available, so it'll be replaced with nothing in a batch file or leave as-is in command line

You need to use delayed expansion and print the variable with !!

cmd.exe /V:ON /c set HOSTNAME=%COMPUTERNAME% && echo !HOSTNAME!

The /V:ON is for enabling delayed expansion

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.

In a batch file it can be enabled by setlocal EnableDelayedExpansion

However for that purpose just cmd.exe /V:ON /c echo %COMPUTERNAME% is enough. Yet it's still not the efficient way. There are better ways to get hostname in Java

Map<String, String> env = System.getenv();
if (env.containsKey("COMPUTERNAME"))
    return env.get("COMPUTERNAME");

or

InetAddress.getLocalHost().getHostName()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM