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.
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
Asked: 2022-05-06 11:00:00 +0000
Seen: 9 times
Last updated: May 30 '22
What is the process for initializing Java UDFs in Spark?
How can set the Project Title in the Doxygen Configuration File?
How can I convert Double to Long in Java?
Can I add a default Parameter for a Method in Java like int calculate(int x, int y=2)?
How can the rejection of the class text_plain from JavaMail API due to a VerifyError be confirmed?
Is it feasible to utilize a Toggle Button to switch among multiple classes exceeding 2?
How can I set up Environment variables on my M1 MacBook and resolve the ZSH permission denied error?