How to run Linux commands in Java? How to run Linux commands in Java? java java

How to run Linux commands in Java?


You can use java.lang.Runtime.exec to run simple code. This gives you back a Process and you can read its standard output directly without having to temporarily store the output on disk.

For example, here's a complete program that will showcase how to do it:

import java.io.BufferedReader;import java.io.InputStreamReader;public class testprog {    public static void main(String args[]) {        String s;        Process p;        try {            p = Runtime.getRuntime().exec("ls -aF");            BufferedReader br = new BufferedReader(                new InputStreamReader(p.getInputStream()));            while ((s = br.readLine()) != null)                System.out.println("line: " + s);            p.waitFor();            System.out.println ("exit: " + p.exitValue());            p.destroy();        } catch (Exception e) {}    }}

When compiled and run, it outputs:

line: ./line: ../line: .classpath*line: .project*line: bin/line: src/exit: 0

as expected.

You can also get the error stream for the process standard error, and output stream for the process standard input, confusingly enough. In this context, the input and output are reversed since it's input from the process to this one (i.e., the standard output of the process).

If you want to merge the process standard output and error from Java (as opposed to using 2>&1 in the actual command), you should look into ProcessBuilder.


You can also write a shell script file and invoke that file from the java code. as shown below

{   Process proc = Runtime.getRuntime().exec("./your_script.sh");                           proc.waitFor();}

Write the linux commands in the script file, once the execution is over you can read the diff file in Java.

The advantage with this approach is you can change the commands with out changing java code.


You need not store the diff in a 3rd file and then read from in. Instead you make use of the Runtime.exec

Process p = Runtime.getRuntime().exec("diff fileA fileB");BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));while ((s = stdInput.readLine()) != null) {        System.out.println(s);}