以编程方式从特定位置运行脚本

时间:2015-10-28 11:54:25

标签: java runtime

我有一个java类,它运行我需要的服务器上的任何脚本,并且它运行良好。

我遇到了一个问题,我需要从特定位置运行一个脚本而不确定如何执行此操作。在我的java方法中运行脚本之前,有没有办法'cd'到目录?

我目前的方法:

public String runScriptFile(String pathname) throws IOException{
    Runtime rt = Runtime.getRuntime();
    String output="";
    Process proc = rt.exec(pathname);

    BufferedReader stdInput = new BufferedReader(new 
         InputStreamReader(proc.getInputStream()));

    BufferedReader stdError = new BufferedReader(new 
         InputStreamReader(proc.getErrorStream()));

    String s = null;
    while ((s = stdInput.readLine()) != null) {
        output+=s;
    }

    while ((s = stdError.readLine()) != null) {
        output+=s;
    }
    return output;
}

2 个答案:

答案 0 :(得分:1)

答案是在Runtime.exec中使用location param,如下所示

Process proc = rt.exec(pathname, null, new File("C:\\files\\"));

答案 1 :(得分:1)

也许this SO answer can help you

您可以设置exec method

的工作目录