此示例演示如何从Java执行外部命令并获取命令结果。在这里,我们简单地ls -al在当前工作目录上执行Linux命令并显示结果。
package org.nhooo.example.lang;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class ProcessResult {
public static void main(String[] args) {
try {
Process process = Runtime.getRuntime().exec("ls -al");
// 等待此过程完成或终止
process.waitFor();
// 获取流程退出值
int exitValue = process.exitValue();
System.out.println("exitValue = " + exitValue);
// 通过读取以下命令来读取ls -al命令的结果
// 流程的输入流
InputStreamReader is = new InputStreamReader(process.getInputStream());
BufferedReader reader = new BufferedReader(is);
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
}以下是我们的程序结果:
exitValue = 0 total 64 drwxr-xr-x 20 wsaryada staff 680 Aug 7 14:13 . drwxr-xr-x 4 wsaryada staff 136 Jun 18 00:33 .. -rw-r--r--@ 1 wsaryada staff 6148 Jun 29 14:04 .DS_Store -rw-r--r-- 1 wsaryada staff 267 May 19 20:47 .editorconfig drwxr-xr-x 16 wsaryada staff 544 Aug 10 08:34 .git -rw-r--r-- 1 wsaryada staff 1535 May 19 20:47 .gitignore drwxr-xr-x 15 wsaryada staff 510 Aug 10 08:34 .idea -rw-r--r-- 1 wsaryada staff 1313 May 19 20:47 LICENSE -rw-r--r-- 1 wsaryada staff 101 May 19 20:47 README.md drwxr-xr-x 5 wsaryada staff 170 Jul 28 23:11 nhooo-basic drwxr-xr-x 6 wsaryada staff 204 Jun 30 14:22 nhooo-commons drwxr-xr-x 6 wsaryada staff 204 Jul 27 15:32 nhooo-lang-package drwxr-xr-x@ 5 wsaryada staff 170 Jun 16 20:49 nhooo-mail drwxr-xr-x 6 wsaryada staff 204 Aug 7 17:22 nhooo-mybatis drwxr-xr-x 5 wsaryada staff 170 Jul 20 10:36 nhooo-poi -rw-r--r-- 1 wsaryada staff 669 Jun 2 14:29 nhooo-project.iml drwxr-xr-x 7 wsaryada staff 238 Jun 26 21:52 nhooo-swing drwxr-xr-x 6 wsaryada staff 204 Aug 3 15:06 nhooo-util-package drwxr-xr-x 6 wsaryada staff 204 Jun 30 15:09 maven-helloworld -rw-r--r-- 1 wsaryada staff 1622 Aug 7 14:13 pom.xml