ProcessBuilder Environment Injection
ProcessBuilder.environment() inherits the parent environment and accepts overrides, so a child process receives staged config without editing global state.
Code
import java.io.IOException;
import java.util.Map;
public class ChildEnvConfig {
public static void main(String[] args) throws IOException {
ProcessBuilder builder = new ProcessBuilder("java", "-version");
// environment() 按需创建子进程环境:默认继承父进程,再追加专属变量
Map<String, String> env = builder.environment();
env.put("DEPLOY_ENV", "staging");
env.put("LOG_LEVEL", "debug");
// 回读注入的键:写进的是子进程可见的环境映射
env.entrySet().stream()
.filter(e -> e.getKey().startsWith("DEPLOY") || e.getKey().startsWith("LOG"))
.forEach(e -> System.out.println(e.getKey() + "=" + e.getValue()));
Process child = builder.start();
System.out.println("exit code: " + child.onExit().join().exitValue()); // 0
}
}The sequence that produces output
ProcessBuilder Environment Injection is built around the class ChildEnvConfig.
The pipeline is a stream: source, lazy intermediate steps, one terminal collector.
Watch out for
- The project needs no addition before the file runs.
Using it
The demo output is labeled (exit code:); each label names the call that printed it.
Key statements
.filter(e -> e.getKey().startsWith("DEPLOY") || e.getKey().startsWith("LOG"))
.forEach(e -> System.out.println(e.getKey() + "=" + e.getValue()));
Interactive Tools for This Topic
Dotenv File ParserParse .env file content into a JSON object, handling comments, export prefixes, single quotes, and double-quoted escape sequences.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.JSON to TOML ConverterTurn a JSON object into TOML, emitting nested objects as tables and arrays of objects as array-of-tables blocks.JSON to YAML ConverterConvert JSON to readable YAML with nested block mappings, sequences, and quoting only where it is required.
FAQ
- What does ProcessBuilder Environment Injection print when run?
- Run it as a complete program — the output lines carry labels such as `exit code:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.