Created
February 5, 2018 22:30
examples of extending string to use processBuilder from there
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
// redirect to stderr/stdout | |
fun String.runCommand(workingDir: File) { | |
ProcessBuilder(*split(" ").toTypedArray()) | |
.directory(workingDir) | |
.redirectOutput(Redirect.INHERIT) | |
.redirectError(Redirect.INHERIT) | |
.start() | |
.waitFor(60, TimeUnit.MINUTES) | |
} | |
// capture output as string | |
fun String.runCommand(workingDir: File): String? { | |
try { | |
val parts = this.split("\\s".toRegex()) | |
val proc = ProcessBuilder(*parts.toTypedArray()) | |
.directory(workingDir) | |
.redirectOutput(ProcessBuilder.Redirect.PIPE) | |
.redirectError(ProcessBuilder.Redirect.PIPE) | |
.start() | |
proc.waitFor(60, TimeUnit.MINUTES) | |
return proc.inputStream.bufferedReader().readText() | |
} catch(e: IOException) { | |
e.printStackTrace() | |
return null | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment