无法使用运行时exec访问环境变量

时间:2013-08-13 01:37:28

标签: java runtime.exec

我正在尝试使用Runtime exec(Java)运行几个.bat命令。问题是在设置环境变量后,我无法使用这些变量。

Runtime rt = Runtime.getRuntime();
Process pr;
pr = rt.exec("cmd.exe /c echo %JAVA_HOME%");
InputStream is;
InputStreamReader isr;
BufferedReader reader ;
String line;
is = pr.getInputStream();
isr = new InputStreamReader(is);
reader = new BufferedReader(isr);

while ((line = reader.readLine()) != null) {
System.out.println(line);
}
reader.close();
pr.getOutputStream().close();`

JAVA_HOME不返回实际的env路径。

1 个答案:

答案 0 :(得分:1)

代码对我来说很完美,

try {
            Runtime rt = Runtime.getRuntime();
            Process pr;
            pr = rt.exec("cmd.exe /c echo %JAVA_HOME%");
            InputStream is;
            InputStreamReader isr;
            BufferedReader reader;
            String line;
            is = pr.getInputStream();
            isr = new InputStreamReader(is);
            reader = new BufferedReader(isr);

            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }

            reader.close();
            pr.getOutputStream().close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

如果它不适合你,

  1. 确保正确定义了环境变量%JAVA_HOME%。启动命令提示符并共享cmd.exe /c echo %JAVA_HOME%
  2. 的输出
  3. 您是否使用任何IDE来运行该程序?