工具类调用

  1. public static void main(String[] args) {
  2. WindowCmdCtrl cmd = new WindowCmdCtrl();
  3. cmd.isPrintCmd(true);//执行之前打印执行的命令,默认为false,可不设置
  4. cmd.setCharset("GBK");//设置返回内容的编码格式为GBK,默认为GBK,可不设置
  5. String tree = cmd.exec("tree",null,"E:\\tool");
  6. System.out.println("E\\tool的文件树为:"+tree);
  7. cmd.exec("notepad");//打开记事本
  8. }

工具类

下载:WindowCmdCtrl.java

  1. import java.io.*;
  2. import java.nio.charset.Charset;
  3. public class WindowCmdCtrl {
  4. private Runtime runtime;
  5. private String charset = "GBK";//编码格式
  6. private boolean isPrintCmd = false;
  7. public WindowCmdCtrl(){
  8. runtime = Runtime.getRuntime();
  9. }
  10. /**
  11. * 设置编码格式
  12. * @param charset
  13. */
  14. public void setCharset(String charset){
  15. if (charset!=null&&!charset.isEmpty()){
  16. this.charset = charset;
  17. }
  18. }
  19. /**
  20. * 是否打印执行的命令
  21. * @param isPrintCmd
  22. */
  23. public void isPrintCmd(boolean isPrintCmd){
  24. this.isPrintCmd = isPrintCmd;
  25. }
  26. /**
  27. * 对文件夹进行cmd操作
  28. *
  29. * @param cmd
  30. * @param envp
  31. * @param dir
  32. * @return
  33. */
  34. public String exec(String cmd, String[] envp, String dir){
  35. if (!cmd.startsWith("cmd /c")){
  36. cmd = "cmd /c "+cmd;
  37. }
  38. if (isPrintCmd){
  39. System.out.println(dir+">"+cmd);
  40. }
  41. try {
  42. return getReply(runtime.exec(cmd, envp, new File(dir)));
  43. }catch (Exception e){
  44. e.printStackTrace();
  45. return null;
  46. }
  47. }
  48. /**
  49. * 执行cmd
  50. * @param cmd 命令
  51. * @return
  52. */
  53. public String exec(String cmd){
  54. if (!cmd.startsWith("cmd /c")){
  55. cmd = "cmd /c "+cmd;
  56. }
  57. if (isPrintCmd){
  58. System.out.println(cmd);
  59. }
  60. try {
  61. return getReply(runtime.exec(cmd));
  62. }catch (Exception e){
  63. e.printStackTrace();
  64. }
  65. return null;
  66. }
  67. /**
  68. * 获取应答
  69. * @param process
  70. * @return
  71. */
  72. private String getReply(Process process){
  73. try{
  74. BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream(), Charset.forName(charset)));
  75. StringBuilder builder = new StringBuilder();
  76. String line;
  77. while ((line=br.readLine())!=null) {
  78. builder.append(line);
  79. builder.append("\r\n");
  80. }
  81. BufferedReader error = new BufferedReader(new InputStreamReader(process.getErrorStream(),Charset.forName(charset)));
  82. String errorLine;
  83. while ((errorLine = error.readLine())!=null) {
  84. builder.append(errorLine);
  85. builder.append("\r\n");
  86. }
  87. return builder.toString();
  88. }catch (Exception e){
  89. e.printStackTrace();
  90. }
  91. return null;
  92. }
  93. public void close(){
  94. if (runtime!=null){
  95. runtime.gc();
  96. }
  97. }
  98. }