How to run Linux commands in Java?

Viewed 194626

I want to create diff of two files. I tried searching for code in Java that does it, but didnt find any simple code/ utility code for this. Hence, I thought if I can somehow run linux diff/sdiff command from my java code and make it return a file that stores the diff then it would be great.

Suppose there are two files fileA and fileB. I should be able to store their diff in a file called fileDiff through my java code. Then fetching data from fileDiff would be no big deal.

9 Answers
ProcessBuilder processBuilder = new ProcessBuilder();

// -- Linux --

// Run a shell command
processBuilder.command("bash", "-c", "ls /home/kk/");

// Run a shell script
//processBuilder.command("path/to/hello.sh");

// -- Windows --

// Run a command
//processBuilder.command("cmd.exe", "/c", "dir C:\\Users\\kk");

// Run a bat file
//processBuilder.command("C:\\Users\\kk\\hello.bat");

try {

    Process process = processBuilder.start();

    StringBuilder output = new StringBuilder();

    BufferedReader reader = new BufferedReader(
            new InputStreamReader(process.getInputStream()));

    String line;
    while ((line = reader.readLine()) != null) {
        output.append(line + "\n");
    }

    int exitVal = process.waitFor();
    if (exitVal == 0) {
        System.out.println("Success!");
        System.out.println(output);
        System.exit(0);
    } else {
        //abnormal...
    }

} catch (IOException e) {
    e.printStackTrace();
} catch (InterruptedException e) {
    e.printStackTrace();
}
Related