Don’t say much, just go to the code.

package org.bood.common.utils;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Properties;

/**
 * 执行命令行命令
 * 
 * @author bood
 * @since 2020/10/16
 */
public class CommandUtils {

	private CommandUtils() {
	}

	/**
	 * <p>
	 * 执行命令
	 * </p>
	 *
	 * @param commandLine: 命令
	 * @return:java.lang.String
	 * @author:bood
	 * @date:2020/10/16
	 */
	public static String execute(String commandLine) throws Exception {
		String[] cmd = new String[3];
		Properties props = System.getProperties();
		String osName = props.getProperty("os.name").toLowerCase();
		String charset=null;
		String result="";

		if (osName.startsWith("windows")) {
			cmd[0] = "cmd.exe";
			cmd[1] = "/C";
			cmd[2] = commandLine;
			charset="GBK";
		} else if (osName.startsWith("linux")) {
			cmd[0] = "sh";
			charset="UTF-8";
		}

		Process ps = Runtime.getRuntime().exec(cmd);
		String line = null;
		BufferedReader input = new BufferedReader(new InputStreamReader(ps.getInputStream(),charset));
		while ((line = input.readLine()) != null) {
			result+=line+"\n";
		}
		input.close();
		ps.destroy();
		return result;
	}

}
Logo

「智能机器人开发者大赛」官方平台,致力于为开发者和参赛选手提供赛事技术指导、行业标准解读及团队实战案例解析;聚焦智能机器人开发全栈技术闭环,助力开发者攻克技术瓶颈,促进软硬件集成、场景应用及商业化落地的深度研讨。 加入智能机器人开发者社区iRobot Developer,与全球极客并肩突破技术边界,定义机器人开发的未来范式!

更多推荐