在java中执行windows和linux指令

在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);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值