Ask Your Question
2

How can a shell script be run in Java and the output be read?

asked 2022-05-06 11:00:00 +0000

huitzilopochtli gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2022-05-30 22:00:00 +0000

devzero gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-05-06 11:00:00 +0000

Seen: 9 times

Last updated: May 30 '22