当前位置: 移动技术网 > IT编程>开发语言>Java > Java运行Linux命令和Windows命令工具类

Java运行Linux命令和Windows命令工具类

2020年07月18日  | 移动技术网IT编程  | 我要评论
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
/**
 * 系统命令执行器
 * @author suozq
 *
 */
public class LocalCmdExecutor {
	private static Runtime rt=Runtime.getRuntime();
	private static String charsetName = "utf-8";
	static {
		String os = System.getProperty("os.name");
		if(os.toLowerCase().contains("windows")) {
			charsetName="gb2312";
		}
	}
	/**
	 * 运行系统命令
	 * @param cmd 例子:exec("javac","-version")或exec(new String[]{"javac","-version"})
	 * @return
	 * @throws IOException
	 */
	public static String exec(String...cmd) throws IOException {
		return handleProcess(rt.exec(cmd));
	}
	
	/**
	 * 运行系统命令
	 * @param cmd 例子:exec("javac -version")
	 * @return
	 * @throws IOException
	 */
	public static String exec(String cmd) throws IOException {
		return handleProcess(rt.exec(cmd));
	}
	
	private static String handleProcess(Process process) throws IOException {
		StringBuilder sb = new StringBuilder();
		BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream(),charsetName));
	    for(String s=reader.readLine();s!=null;s=reader.readLine()) {
	    	sb.append(s).append("\n");
	    }
	    reader.close();
	    return sb.toString();
	}
	
	public static void main(String[] args) throws IOException {
		System.out.println(exec("javac -version"));
	}
}

注意

  • 推荐使用数组方式,使用字符串最终还是需要转为字符串数组;
  • Runtime对象是单例模式,无论调用多少次Runtime.getRuntime(),返回为同一对象;
  • rt.exec()从源码看可以并发调用,并发使用时,资源耗用可能会很大;
  • 如果命令执行过慢,会导致不能读取到结果,请添加process.waitFor()方法,该方法会使当前线程等待直到process子进程结束,0代表正常结束

本文地址:https://blog.csdn.net/suo082407128/article/details/107386044

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网