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;
}
}
}