System.getenv()&的区别System.getProperty()

时间:2012-10-28 19:05:17

标签: java environment-variables

  

可能重复:
  What’s the difference between a System property and environment variable

System.getenv()& System.getProperty()?

当我们使用Processbuilder运行任何命令时,我们可以设置环境变量,即:

String[] vCmd = { System.getenv("ANT_HOME") + "/bin/ant", "-f",
                ANT_BUILD_FILE, TARGET };
        ProcessBuilder pb = new ProcessBuilder(vCmd);
        Map<String, String> env = pb.environment();     
        env.put("CLASSPATH",
                antHome+"/lib/ant.jar:"
                        + antHome+"/lib/ant-launcher.jar:"
                        + antHome+"/lib/ant-nodeps.jar:"
                        );
        try{

            Process process = pb.start();
            InputStream is = process.getInputStream();
            InputStreamReader isr = new InputStreamReader(is);
            BufferedReader br = new BufferedReader(isr);
            String line;
            while ((line = br.readLine()) != null) {
                System.out.println(line);
            }
            pb.wait();
        }
        catch(Exception e)

            System.out.println(e.getMessage());


        }

如果我在此方法之前使用System.setProperties()设置了一些属性,那么ProcessBuilder启动此进程是否可用?

2 个答案:

答案 0 :(得分:157)

getenv获取环境变量getProperty获取Java属性。环境变量在OS级别指定。通过将-D选项传递给JVM来指定Java属性(并且可以通过编程方式设置)。

答案 1 :(得分:27)

System.getenv()用于操作系统环境变量,而System.getProperty()用于JVM参数,它们作为-DpropName=value传递给Java应用程序启动器(java)。