在java代码中执行windows和linux指令
通过Runtime类来执行,Runtime其他作用未详细了解
以下为实列仅在windows和linux测试过,亲测有效。
import java.io.InputStream;
import org.apache.commons.io.IOUtils;
/**
* 测试cmd命令
*/
public static void cmd() {
Runtime runtime = Runtime.getRuntime();
// 该执行的命令
String stmt = "java -version";
try {
String osName = System.getProperties().getProperty("os.name"); // 操作系统名称
String[] command;
if (osName.contains("Windows")) {// Windows下
String[] content = { "cmd", "/c", stmt };
command = content;
} else {// linux下
String[] content = { "/bin/sh", "-c", stmt };
command = content;
}
Process process = runtime.exec(command);
//-------1----------
InputStream input = process.getInputStream();
System.out.println("写入:" + IOUtils.toString(input, "UTF-8"));
// 若有信息则输出
InputStream errorStream = process.getErrorStream();
System.out.println("信息:\r\n" + IOUtils.toString(errorStream, "UTF-8"));
if (input != null) {
input.close();
if (errorStream != null) {
errorStream.close();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
注:此处记录一个小知识,关闭流可以采用java新特性try(){}...catch,括号中的流会结束后自动关闭,如下
// 关闭流新特性try()...catch
try (InputStream input = process.getInputStream(); InputStream errorStream = process.getErrorStream();) {
System.out.println("写入:" + IOUtils.toString(input, "UTF-8"));
// 若有信息则输出
System.out.println("信息:\r\n" + IOUtils.toString(errorStream, "UTF-8"));
} catch (Exception e) {
e.printStackTrace();
}
输出结果:
写入:
信息:
java version "1.8.0_31"
Java(TM) SE Runtime Environment (build 1.8.0_31-b13)
Java HotSpot(TM) 64-Bit Server VM (build 25.31-b07, mixed mode)
总结:
总结下来主要就是这三行代码:
Windows下调用系统命令:String [] cmd={"cmd","/C","指令"};
Linux下调用系统命令:String [] cmd={"/bin/sh","-c","指令"};
通过Runtime调用指令:Process process = Runtime.getRuntime().exec(cmd);