Nawaf Abdu Nawaf Abdu - 5 months ago 17
Java Question

Java how can I execute/run specific file by his path

I want to execute/run this file using Java.
The path is "/usr/local/studio.sh"

I tried:

public class Main {

public static void main(String[] args) {

String[] cmd = {"cd /usr/local","./studio.sh"};
try {
Process p = Runtime.getRuntime().exec(cmd);


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

} }


but it doesn't work. Is there another way?

Answer

You can use ProcessBuilder (see https://docs.oracle.com/javase/7/docs/api/java/lang/ProcessBuilder.html) and set the working directory using directory(...) instead of cd command.

In the end something like this:

ProcessBuilder pb = new ProcessBuilder("/usr/bin/bash","/usr/local/studio.sh")
pb.directory(...);
pb.redirectErrorStream(true);
Process p = pb.start();
IOUtils.copy(p.getInputStream(), System.out);
p.waitFor();