Running Bash commands in Java

You start a new process with Runtime.exec(command). Each process has a working directory. This is normally the directory in which the parent process was started, but you can change the directory in which your process is started. I would recommend to use ProcessBuilder ProcessBuilder pb = new ProcessBuilder(“ls”); pb.inheritIO(); pb.directory(new File(“bin”)); pb.start(); If you want … Read more

Execute external program

borrowed this shamely from here Process process = new ProcessBuilder(“C:\\PathToExe\\MyExe.exe”,”param1″,”param2″).start(); InputStream is = process.getInputStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); String line; System.out.printf(“Output of running %s is:”, Arrays.toString(args)); while ((line = br.readLine()) != null) { System.out.println(line); } More information here Other issues on how to pass commands here and here

Java Runtime.getRuntime().exec() alternatives

I found a workaround in this article, basically the idea is that you create a process early on in the startup of your application that you communicate with (via input streams) and then that subprocess executes your commands for you. //you would probably want to make this a singleton public class ProcessHelper { private OutputStreamWriter … Read more

Runtime.exec().waitFor() doesn’t wait until process is done

By using start, you are askingcmd.exe to start the batch file in the background: Process p = Runtime.getRuntime().exec(“cmd /c start ” + path + “\\RunFromCode.bat”); So, the process which you launch from Java (cmd.exe) returns before the background process is finished. Remove the start command to run the batch file in the foreground – then, … Read more

read the output from java exec

Use getErrorStream(). BufferedReader in = new BufferedReader(new InputStreamReader(pr.getErrorStream())); EDIT: You can use ProcessBuilder (and also read the documentation) ProcessBuilder ps=new ProcessBuilder(“java.exe”,”-version”); //From the DOC: Initially, this property is false, meaning that the //standard output and error output of a subprocess are sent to two //separate streams ps.redirectErrorStream(true); Process pr = ps.start(); BufferedReader in = new … Read more