public CMDUtils(String cmds) { this.cmds = cmds; }
public String getCmds() { return cmds; }
public void setCmds(String cmds) { this.cmds = cmds; }
public Object cmd(){ System.out.println("执行的命令是:"+this.cmds); String[] cmd = new String[]{"/bin/sh", "-c", this.cmds}; Process process = null; try { process = Runtime.getRuntime().exec(cmd);
BufferedReader buffer = new BufferedReader(new InputStreamReader(process.getInputStream())); StringBuffer stringBuffer = new StringBuffer(); String line; while ((line = buffer.readLine()) != null) { stringBuffer.append(line).append("\n"); } String result = stringBuffer.toString(); System.out.println("执行的结果是:================================="); System.out.println(result); return result; } catch (IOException e) { e.printStackTrace(); return null; }
} }
这样执行过命令后会返回对应的执行结果。测试代码如下:
1 2 3 4 5 6 7 8 9 10
public class MyTest { public static void main(String args[]) { System.out.println("hello world"); String cmds = "df -h"; CMDUtils cmdUtils = new CMDUtils(cmds); String result = (String) cmdUtils.cmd(); System.out.println("我拿到的结果是:============================"); System.out.println(result); } }