ProcessBuilder environment variable in java

后端 未结 2 934
既然无缘
既然无缘 2020-12-09 05:53

I\'m trying to add a environment variable for a ProcessBuilder object but then when I call on that new variable in the ProcessBuilder I get an error. this is how I build the

2条回答
  •  清歌不尽
    2020-12-09 06:19

    This works for me in Windows:

    @Test
    public void testProcessBuilder() throws IOException {
        ProcessBuilder processBuilder = new ProcessBuilder("cmd.exe", "/C", "echo Hello %name%");
        Map environment = processBuilder.environment();
        environment.put("name", "Alfredo Osorio");
        Process p = processBuilder.start();
        String line;
        BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream()));
        while ((line = r.readLine()) != null) {
            System.out.println(line);
        }
        r.close();
    }
    

    Output:

    Hello Alfredo Osorio

    As you can see in Windows you use the %environmentVariable% instead of the $environementVariable

提交回复
热议问题