JAVA 執行 dos/shell命令的實現

JAVA 執行 dos/shell命令的實現

1、獲取系統類型

2、linux下執行

3、windows下執行

4、執行結果返回。


package com.fw.common;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
 
 
/**
 * @author 
 * 執行系統命令
 */
public class MComand {
	public static void main(String args[]){
		try {
			ResultBean rbean=exec("dir");
			System.out.println("state:"+rbean.state);
			System.out.println("runCode:"+rbean.getRunCode());
			System.out.println("message:"+rbean.getMessage());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	
	/**
	 * 執行腳本命令
	 */
	public static ResultBean exec(String comand)throws Exception{
		String system=system();
		if(system.equals("windows")){
			return windows(comand);
		}else if(system.equals("linux")){
			return linux(comand);
		}
		return null;
	}
	
	/**
	 * 獲取操作系統
	 */
	protected static String system(){
		String system= System.getProperty("os.name").toLowerCase();
		return system.contains("windows")?"windows":system.contains("linux")?"linux":"";
	}
	
	/**
	 * windows下執行命令
	 */
	protected static ResultBean windows(String cmd)throws Exception{ 
        Process process = Runtime.getRuntime().exec("cmd /c "+cmd);   
        return run_(process);	
	}
	/**
	 * linux下執行命令
	 */
	protected static ResultBean linux(String shell)throws Exception{ 
		String[] shellA={"/bin/sh","-c",shell};
        Process process = Runtime.getRuntime().exec(shellA);
        return run_(process);	 
	}
	
	protected static ResultBean run_( Process process)throws Exception{
		ResultBean rbean=new ResultBean();
		StringBuffer sb = new StringBuffer();   
		 BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream(), Charset.forName("GBK")));  
	        String line = null;  
	        while ((line = br.readLine()) != null) {  
	        	sb.append(line).append("\n");  
	        }    
	        int runCode=process.waitFor(); 
	        if(runCode == 0){
	        	rbean.state=true;
	        	rbean.setRunCode(runCode);
	        	rbean.setMessage(sb.toString());
	        }else{
	        	rbean.state=false;
	        	rbean.setRunCode(runCode);
	        	rbean.setMessage("命令執行失敗");
	        }
	        return rbean;
	}
	
	static class ResultBean{
		private boolean state;			//執行是否成功
		private int runCode;			//系統返回碼
		private String message;			//系統返回值(執行失敗的時候返回錯誤原因描述)
		public boolean isState() {
			return state;
		}
		public void setState(boolean state) {
			this.state = state;
		}
		
		public int getRunCode() {
			return runCode;
		}
		public void setRunCode(int runCode) {
			this.runCode = runCode;
		}
		public String getMessage() {
			return message;
		}
		public void setMessage(String message) {
			this.message = message;
		}
		
	}
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章