本篇文章给大家介绍一下“Java.Utils:”执行命令行命令的方法。有一定的参考价值,有需要的朋友可以参考一下,希望对大家有所帮助。

Java.Utils:如何执行命令行命令-LMLPHP

package org.bood.common.utils;import java.io.BufferedReader;import java.io.InputStreamReader;import java.util.Properties;/**
 * <p>
 * 执行命令行命令
 * </p>
 * 
 * @author:bood
 * @date:2020/10/16
 */public class CommandUtils {

	public 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;
	}}
登录后复制

推荐:《java视频教程

以上就是Java.Utils:如何执行命令行命令的详细内容,更多请关注Work网其它相关文章!

09-09 07:48