1

我正在尝试使用 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 不返回实际的环境路径。

4

1 回答 1

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. 您是否使用任何 IDE 来运行程序?
于 2013-08-13T01:59:36.547 回答