如何使用Java Runtime执行文件

时间:2011-12-01 15:02:58

标签: java ant runtime.exec

我正在尝试使用Runtime.getRuntime()执行一个简单的批处理文件.exec(command); 但面临问题, 下面是我的代码片段

public class Path {
        public static void main(String args[]){
            String[] command = new String[3];
            command[0]="cmd";
            command[1]="/C";
            command[2]="D:/alt/a.bat";
    Process p;
        try {
            p = Runtime.getRuntime().exec(command);
            BufferedReader stdInput = new BufferedReader(new InputStreamReader(
                    p.getInputStream()));
            BufferedReader stdError = new BufferedReader(new InputStreamReader(
                    p.getErrorStream()));
            String s = null;
            while ((s = stdInput.readLine()) != null) {
                System.out.println(s);
            }
            while ((s = stdError.readLine()) != null) {
                System.out.println(s);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

并且批处理a.bat中包含ant -f runme.xml测试 runme.xml驻留在D:/ alt物理位置,它有一个目标测试,到目前为止一直很好 但是当我尝试执行上面的java代码时,下面是输出

D:\RCPStack\Path>ant -f runme.xml test  Buildfile: runme.xml does not
exist! Build failed

当我手动执行它工作正常,似乎问题是与代码 以下是手动执行输出 enter image description here

如何解决这个问题(我不知道代码是否错误)并将其作为最佳实践处理

2 个答案:

答案 0 :(得分:3)

尝试使用方法Runtime.exec(String cmd, String[] envp, File dir) 将工作目录设置为D:/alt/

这是因为Ant必须在runme.xml所在的目录中执行,因此Ant可以找到它。

答案 1 :(得分:0)

p=Runtime.getRuntime().exec("cmd /c ant -f runme.xml test", null, new File("D:/alt"));//works

p=Runtime.getRuntime().exec("cmd /c a.bat", null, new File("D:/alt"));//works
相关问题