ProcessBuilder Argument List Execution
Run external commands safely through ProcessBuilder argument lists with streamed output, a hard timeout, and destroyForcibly cleanup.
Code
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.concurrent.TimeUnit;
public class SafeCommand {
public static void main(String[] args) throws Exception {
Path workdir = Files.createTempDirectory("safe-cmd");
// 参数以 List 传递:不经 shell 解析,用户输入无法注入额外命令
List<String> command = List.of("git", "-C", workdir.toString(), "init", "--quiet");
Process process = new ProcessBuilder(command)
.redirectErrorStream(true)
.directory(workdir.toFile())
.start();
boolean finished = process.waitFor(10, TimeUnit.SECONDS);
if (!finished) {
process.destroyForcibly();
process.waitFor();
throw new IllegalStateException("command timed out: " + command.get(0));
}
String output = new String(process.getInputStream().readAllBytes());
System.out.println("exit=" + process.exitValue());
if (!output.isBlank()) {
System.out.println(output.strip());
}
}
}How it works
Count the class SafeCommand as the entire surface area of ProcessBuilder Argument List Execution.
Invalid states are rejected up front: it throws IllegalStateException instead of continuing with bad data.
Putting it to use
The demo output is labeled (exit=), so every printed line maps back to its originating operation.
Core lines
throw new IllegalStateException("command timed out: " + command.get(0));
Interactive Tools for This Topic
Argon2id Hash InfoEstimate Argon2id password-hash latency and memory usage, and check your parameters against OWASP 2024 minimum and recommended settings.bcrypt Cost EstimatorEstimate bcrypt cost factor latency and brute-force resistance, and get a recommended cost for your target hash time and attacker throughput.CORS Header Policy DebuggerSimulate browser CORS preflight and credential policies against server response headers to pinpoint blocked origins, methods, or headers and fix them.CSP Header BuilderBuild a Content-Security-Policy header from per-directive sources, skipping empty ones and rejecting a blanket wildcard.
FAQ
- What happens on invalid input?
- It throws `IllegalStateException` before any real work runs — handle it at the call site or let it propagate deliberately.
- What does ProcessBuilder Argument List Execution print when run?
- Running the file directly is enough — expect labeled output lines such as `exit=`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.