实现说明
ProcessBuilder 注入子进程环境可以归结为类 ChildEnvConfig。
管道就是一个 stream:数据源、惰性中间步骤、一个终端收集器。
使用要点
- 跑完文件,输出里会留下标记——
exit code:。
常见问题
运行「ProcessBuilder 注入子进程环境」会打印什么?
不用做任何设置,直接把文件跑完——输出里的 exit code: 标签标明各步骤。
核心语句
.filter(e -> e.getKey().startsWith("DEPLOY") || e.getKey().startsWith("LOG"))
.forEach(e -> System.out.println(e.getKey() + "=" + e.getValue()));
代码示例
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
}
}