|
@@ -13,29 +13,34 @@ import org.slf4j.LoggerFactory;
|
|
|
/**
|
|
/**
|
|
|
* 示例一:通过 ProcessBuilder 构建并启动子进程。
|
|
* 示例一:通过 ProcessBuilder 构建并启动子进程。
|
|
|
*
|
|
*
|
|
|
- * 用 ProcessBuilder 指定要运行的命令,调用 start() 启动子进程;
|
|
|
|
|
|
|
+ * 案例点:通过 ProcessBuilder 构建 Process
|
|
|
* 子进程为 src/main/resources/code/hello/Main.java(向标准输出打印两行后正常退出)。
|
|
* 子进程为 src/main/resources/code/hello/Main.java(向标准输出打印两行后正常退出)。
|
|
|
*/
|
|
*/
|
|
|
public class QuickStart {
|
|
public class QuickStart {
|
|
|
private static final Logger log = LoggerFactory.getLogger(QuickStart.class);
|
|
private static final Logger log = LoggerFactory.getLogger(QuickStart.class);
|
|
|
|
|
+ private static final File WORK_DIR = Paths.get(System.getProperty("user.dir"),
|
|
|
|
|
+ "src", "main", "resources", "code", "hello").toFile();
|
|
|
|
|
|
|
|
public static void main(String[] args) throws IOException, InterruptedException {
|
|
public static void main(String[] args) throws IOException, InterruptedException {
|
|
|
- // 子进程程序所在目录(相对当前工程根目录),先编译再运行
|
|
|
|
|
- File workDir = Paths.get(System.getProperty("user.dir"), "src", "main", "resources", "code", "hello").toFile();
|
|
|
|
|
- Jdk.compileFixture(workDir);
|
|
|
|
|
|
|
+ Jdk.compileFixture(WORK_DIR);
|
|
|
|
|
+ buildProcess();
|
|
|
|
|
+ }
|
|
|
|
|
|
|
|
- // 1. 通过 ProcessBuilder 构建命令并启动子进程:
|
|
|
|
|
- // 命令要素 = 可执行文件绝对路径 + Main 类名;directory() 指定子进程的工作目录
|
|
|
|
|
|
|
+ /**
|
|
|
|
|
+ * 案例点:用 ProcessBuilder 构建并启动子进程
|
|
|
|
|
+ * 命令要素 = 可执行文件绝对路径 + Main 类名;directory() 指定子进程工作目录。
|
|
|
|
|
+ */
|
|
|
|
|
+ private static void buildProcess() throws IOException, InterruptedException {
|
|
|
Process process = new ProcessBuilder(Jdk.java(), "-Dfile.encoding=UTF-8", "Main")
|
|
Process process = new ProcessBuilder(Jdk.java(), "-Dfile.encoding=UTF-8", "Main")
|
|
|
- .directory(workDir)
|
|
|
|
|
|
|
+ .directory(WORK_DIR)
|
|
|
.start();
|
|
.start();
|
|
|
|
|
|
|
|
- // 2. 读取子进程的标准输出(println 输出的内容)
|
|
|
|
|
|
|
+ // 读取子进程的标准输出(println 输出的内容)
|
|
|
new BufferedReader(new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8))
|
|
new BufferedReader(new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8))
|
|
|
.lines()
|
|
.lines()
|
|
|
.forEach(line -> log.info("子进程标准输出: {}", line));
|
|
.forEach(line -> log.info("子进程标准输出: {}", line));
|
|
|
|
|
|
|
|
- // 3. 等待子进程结束,返回退出状态码,0 表示正常退出
|
|
|
|
|
|
|
+ // 等待子进程结束,返回退出状态码,0 表示正常退出
|
|
|
int exitStatus = process.waitFor();
|
|
int exitStatus = process.waitFor();
|
|
|
log.info("子进程退出状态码: {}", exitStatus);
|
|
log.info("子进程退出状态码: {}", exitStatus);
|
|
|
}
|
|
}
|