ProcessBuilder environment variable in java

后端 未结 2 927
既然无缘
既然无缘 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:11

    Alfredo O's example gives you the right idea. You need to tell the ProcessBuilder what program to use to execute your command. In this case bash with the "-c" switch, which tells bash to interpret what comes next (i.e. "echo $u") as a command.

    import java.io.BufferedReader;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.util.ArrayList;
    import java.util.Map;
    
    public class OTU {
        public static void main(String[] args) throws Exception {
            ProcessBuilder pb = new ProcessBuilder("/bin/bash", "-c", "echo $u");
            Map env = pb.environment();
            // set environment variable u
            env.put("u", "util/");
    
            Process p = pb.start();
            String output = loadStream(p.getInputStream());
            String error = loadStream(p.getErrorStream());
            int rc = p.waitFor();
            System.out.println("Process ended with rc=" + rc);
            System.out.println("\nStandard Output:\n");
            System.out.println(output);
            System.out.println("\nStandard Error:\n");
            System.out.println(error);
        }
    
        private static String loadStream(InputStream s) throws Exception {
            BufferedReader br = new BufferedReader(new InputStreamReader(s));
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = br.readLine()) != null)
                sb.append(line).append("\n");
            return sb.toString();
        }
    }
    

    This produces the following output:

    Process ended with rc=0
    
    Standard Output:
    
    util/
    
    
    Standard Error:
    

提交回复
热议问题