命令行程序可以帮助我们做很多事情。日常开发中经常需要使用命令。但有时候我们需要在程序中使用命令行程序。Java如何调用命令行程序(主要是linux下命令)呢?
每个 Java 应用程序都有一个 Runtime 类实例,使应用程序能够与其运行的环境相连接。可以通过 getRuntime 方法获取当前运行时。应用程序不能创建自己的 Runtime 类实例。
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
/**
* Created by hutaishi on 2017/3/29.
*/
public class Main {
public static void main(String[] args) {
InputStream in = null;
String[] cmd = new String[]{"cmd.exe", "/C", "ipconfig"};
try {
Process process = Runtime.getRuntime().exec(cmd);
in = process.getInputStream();
BufferedReader read = new BufferedReader(new InputStreamReader(in, "GBK"));
String line = null;
while ((line = read.readLine()) != null) {
System.out.println(line);
}
int exitValue = process.waitFor();
System.out.println("返回值:" + exitValue);
process.getOutputStream().close(); // 不要忘记了一定要关
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
输出如下: