Java - 执行命令行命令

package com.boob.common.utils;

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

/**
 * @description:执行命令行命令
 * @author:boob
 * @since:2020/2/7
 */
public class CommandUtils {

	public CommandUtils() {
	}

	/**
	 * 执行命令
	 * @param commandLine
	 * @return String 执行结果
	 * @throws Exception
	 */
	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;
	}

}
发布了21 篇原创文章 · 获赞 320 · 访问量 8296

猜你喜欢

转载自blog.csdn.net/BUG_call110/article/details/104300310
今日推荐