Home > Java > javaTutorial > Java.Utils: How to execute command line commands

Java.Utils: How to execute command line commands

醉折花枝作酒筹
Release: 2021-04-28 09:27:48
forward
2102 people have browsed it

This article will introduce to you how to execute command line commands with "Java.Utils:". It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.

Java.Utils: How to execute command line commands

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;
	}}
Copy after login

Recommended: "java video tutorial"

The above is the detailed content of Java.Utils: How to execute command line commands. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template