工具类调用
public static void main(String[] args) { WindowCmdCtrl cmd = new WindowCmdCtrl(); cmd.isPrintCmd(true);//执行之前打印执行的命令,默认为false,可不设置 cmd.setCharset("GBK");//设置返回内容的编码格式为GBK,默认为GBK,可不设置 String tree = cmd.exec("tree",null,"E:\\tool"); System.out.println("E\\tool的文件树为:"+tree); cmd.exec("notepad");//打开记事本 }
工具类
下载:WindowCmdCtrl.java
import java.io.*;import java.nio.charset.Charset;public class WindowCmdCtrl { private Runtime runtime; private String charset = "GBK";//编码格式 private boolean isPrintCmd = false; public WindowCmdCtrl(){ runtime = Runtime.getRuntime(); } /** * 设置编码格式 * @param charset */ public void setCharset(String charset){ if (charset!=null&&!charset.isEmpty()){ this.charset = charset; } } /** * 是否打印执行的命令 * @param isPrintCmd */ public void isPrintCmd(boolean isPrintCmd){ this.isPrintCmd = isPrintCmd; } /** * 对文件夹进行cmd操作 * * @param cmd * @param envp * @param dir * @return */ public String exec(String cmd, String[] envp, String dir){ if (!cmd.startsWith("cmd /c")){ cmd = "cmd /c "+cmd; } if (isPrintCmd){ System.out.println(dir+">"+cmd); } try { return getReply(runtime.exec(cmd, envp, new File(dir))); }catch (Exception e){ e.printStackTrace(); return null; } } /** * 执行cmd * @param cmd 命令 * @return */ public String exec(String cmd){ if (!cmd.startsWith("cmd /c")){ cmd = "cmd /c "+cmd; } if (isPrintCmd){ System.out.println(cmd); } try { return getReply(runtime.exec(cmd)); }catch (Exception e){ e.printStackTrace(); } return null; } /** * 获取应答 * @param process * @return */ private String getReply(Process process){ try{ BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream(), Charset.forName(charset))); StringBuilder builder = new StringBuilder(); String line; while ((line=br.readLine())!=null) { builder.append(line); builder.append("\r\n"); } BufferedReader error = new BufferedReader(new InputStreamReader(process.getErrorStream(),Charset.forName(charset))); String errorLine; while ((errorLine = error.readLine())!=null) { builder.append(errorLine); builder.append("\r\n"); } return builder.toString(); }catch (Exception e){ e.printStackTrace(); } return null; } public void close(){ if (runtime!=null){ runtime.gc(); } }}