Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java ProcessBuilder Output to String

How to redirect or get the system output to String?

ProcessBuilder pb = new ProcessBuilder().inheritIO();
...

for (...){
    pb.command(...);
    pb.start();

    //here >>> assign output string to variable
}
like image 969
JR Galia Avatar asked May 20 '26 14:05

JR Galia


1 Answers

Here is an opinion on how to capture the standard output of a system command process into a string container.

Adapted from the web:

try {
  ProcessBuilder pb = new ProcessBuilder("echo", "dummy io");
  final Process p=pb.start();
  BufferedReader br=new BufferedReader(new InputStreamReader(p.getInputStream()));
  String line;
  StringBuilder sb = new StringBuilder();
  while((line=br.readLine())!=null) sb.append(line);
}

System.out.println(sb.toString());
like image 105
Hypersoft Systems Avatar answered May 22 '26 10:05

Hypersoft Systems



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!