Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

One way to run a shell script in Java and read its output is to use the ProcessBuilder class. Here's an example:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class ShellScriptExample {
    public static void main(String[] args) throws IOException {
        ProcessBuilder pb = new ProcessBuilder("path/to/script.sh");
        pb.redirectErrorStream(true);
        Process process = pb.start();
        InputStream is = process.getInputStream();
        InputStreamReader isr = new InputStreamReader(is);
        BufferedReader br = new BufferedReader(isr);
        String line;
        while ((line = br.readLine()) != null) {
            System.out.println(line);
        }
    }
}

In this example, we first create a ProcessBuilder instance and specify the path to the shell script we want to run. We then set the redirectErrorStream property to true so that any error messages from the script will also be included in the output. We start the process and get its input stream, which we pass to an InputStreamReader and then a BufferedReader to read the output line by line. We simply print each line to the console, but you could do anything else you need with the output.