Skip to content

Instantly share code, notes, and snippets.

@dhsrocha
Created February 27, 2021 03:39
Show Gist options
  • Save dhsrocha/d06529d40899f065e39e8acc161bd8b1 to your computer and use it in GitHub Desktop.
Save dhsrocha/d06529d40899f065e39e8acc161bd8b1 to your computer and use it in GitHub Desktop.
Practical sample (Java 8+) for `Runtime.exec` and output returning.
package template;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import lombok.NonNull;
import lombok.SneakyThrows;
import lombok.experimental.UtilityClass;
import lombok.val;
@UtilityClass
class Exec {
@SneakyThrows
static String exec(final @NonNull String cmd) {
val pr = Runtime.getRuntime().exec(cmd);
pr.waitFor(3, TimeUnit.SECONDS);
val out = new BufferedReader(new InputStreamReader(pr.getInputStream(),
StandardCharsets.UTF_8));
return out.lines().collect(Collectors.joining());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment