Last active
April 14, 2021 20:15
-
-
Save SCP002/1b8995970e1340abc6653bba5bc0ac85 to your computer and use it in GitHub Desktop.
Java 8: Start process. Keep StdOut and StdErr in the original order. Display output real time character by character. Capture output on exit.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package org.example; | |
import java.io.IOException; | |
import java.io.InputStream; | |
import java.util.Scanner; | |
public class ProcessExample { | |
public static void main(String[] args) { | |
ProcessBuilder pb = new ProcessBuilder(); | |
pb.command("my-executable-name", "arg1"); | |
// Fix "ERROR: Input redirection is not supported, exiting the process immediately" on Windows: | |
pb.redirectInput(ProcessBuilder.Redirect.INHERIT); | |
// Redirect StdErr to StdOut: | |
pb.redirectErrorStream(true); | |
try { | |
Process proc = pb.start(); | |
String out = captureOut(proc.getInputStream()); | |
int exitCode = proc.waitFor(); | |
System.out.println("------------------------------"); | |
System.out.println(out); | |
System.out.println("Exit code:" + exitCode); | |
} catch (IOException | InterruptedException e) { | |
e.printStackTrace(); | |
} | |
} | |
private static String captureOut(final InputStream src) { | |
StringBuilder sb = new StringBuilder(); | |
Scanner scanner = new Scanner(src); | |
scanner.useDelimiter(""); | |
while (scanner.hasNext()) { | |
String symbol = scanner.next(); | |
System.out.print(symbol); | |
sb.append(symbol); | |
} | |
return sb.toString(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment