Last active
April 20, 2023 08:57
-
-
Save hurtigcodes/320d1370a5342b56691d697d2cc2cf2e to your computer and use it in GitHub Desktop.
Notes: using ProcessBuilder API with pipelines
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
public static void main(String[] args) throws IOException, InterruptedException { | |
String homeDirectory = System.getProperty("user.home"); | |
ProcessBuilder processBuilder = new ProcessBuilder("/bin/sh", "-c", "echo hello"); | |
ProcessBuilder processBuilder2 = new ProcessBuilder("/bin/sh", "-c", "src/script.sh"); | |
// inheritIO() method we see the output of a simple command in the console in our IDE. | |
// use this method when we want to redirect the sub-process I/O to the standard I/O of the current process: | |
processBuilder.inheritIO(); | |
// ProcessBuilder processBuilder = new ProcessBuilder( "node", "-v"); | |
// redirect any errors to stdout | |
processBuilder.redirectErrorStream(true); | |
File log = new File("script.log"); | |
// processBuilder.redirectOutput(log); | |
// processBuilder.directory(new File("src")); | |
Process process = processBuilder.start(); | |
// read stdout unless inheritIO | |
String results = readStream(process.getInputStream()); | |
int exitCode = process.waitFor(); | |
System.out.println("Result: " + results + " Exit code: " + exitCode); | |
// using Java 9 process builder pipelines | |
List<ProcessBuilder> builders = Arrays.asList( | |
new ProcessBuilder("find", "src", "-name", "*.java", "-type", "f"), | |
new ProcessBuilder("wc", "-l")); | |
System.out.println("testing " + readStream(startPipeline(builders).getInputStream())); | |
// same works even without a pipe | |
// List<ProcessBuilder> builders = List.of( | |
// new ProcessBuilder("find", "src", "-type", "f")); | |
} | |
public static String readStream(InputStream inputStream) throws IOException { | |
int bufferSize = 1024; | |
char[] buffer = new char[bufferSize]; | |
StringBuilder out = new StringBuilder(); | |
Reader in = new InputStreamReader(inputStream, StandardCharsets.UTF_8); | |
for (int numRead; (numRead = in.read(buffer, 0, buffer.length)) > 0; ) { | |
out.append(buffer, 0, numRead); | |
} | |
return out.toString(); | |
} | |
public static Process startPipeline(List<ProcessBuilder> builders) throws IOException, InterruptedException { | |
List<Process> processes = ProcessBuilder.startPipeline(builders); | |
Process last = processes.get(processes.size() - 1); | |
// String output = readStream(last.getInputStream()); | |
// System.out.println("Pipeline output: " + output); | |
return last; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment