1

I have a java class that runs any scripts on my server i require, and it works nicely.

I have an issue however, i need to run one script from a specific location and not sure how to do that. Is there a way to 'cd' to a directory before running my script in my java method?

My current method:

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;
}
Fearghal
  • 10,569
  • 17
  • 55
  • 97
  • Maybe this can help you: http://stackoverflow.com/questions/26697916/running-a-bash-command-in-different-directory-from-a-java-program – Tobi Oct 28 '15 at 12:05
  • Yes that was indeed the same way i ended up solving it, probably a bit of a duplicate post so if you want to answer i'll mark ya as correct. – Fearghal Oct 28 '15 at 12:09

2 Answers2

1

Answer is to use the location param in Runtime.exec as follows

Process proc = rt.exec(pathname, null, new File("C:\\files\\"));
Fearghal
  • 10,569
  • 17
  • 55
  • 97
1

Maybe this SO answer can help you

You can set the working directory for the exec method

Community
  • 1
  • 1
Tobi
  • 924
  • 1
  • 10
  • 39