JAVA:調用cmd指令(支持多次手工輸入)


JDK開發環境:1.8

  1 package com.le.tool;
  2 
  3 import java.io.BufferedReader;
  4 import java.io.File;
  5 import java.io.IOException;
  6 import java.io.InputStream;
  7 import java.io.InputStreamReader;
  8 import java.io.PrintWriter;
  9 import java.nio.charset.Charset;
 10 
 11 /**
 12  * java調用cmd指令工具類
 13  * 
 14  * @author le.li
 15  * 
 16  */
 17 public class ExecuteUtil {
 18     /**
 19      * 避免亂碼,如果沒有傳入語言編號,默認使用英文437<br>
 20      * D:\>chcp /? 顯示或設置活動代碼頁編號。<br>
 21      * CHCP [nnn]<br>
 22      * nnn 指定代碼頁編號。<br>
 23      * 不帶參數鍵入 CHCP 以顯示活動代碼頁編號。<br>
 24      */
 25     private static final String DEFAULT_LANGUAGE_CODE = "437";
 26 
 27     /**
 28      * window系統默認語言:GBK
 29      */
 30     private static final String DEFAULT_LANGUAGE = "GBK";
 31 
 32     public static void main(String[] args) {
 33         // executeLink();
 34         
 35         // executeCmd("dir .");
 36         
 37         // 舉例直接把bat文件當cmd指令調用
 38         String cmd = null;
 39         String fileName = "test.bat";
 40         File f = new File(".");
 41         try {
 42             cmd = f.getCanonicalPath() + File.separator + fileName;
 43         } catch (IOException e) {
 44             // e.printStackTrace();
 45             System.err.println("get cmd file error.");
 46         }
 47         executeCmd(cmd);
 48     }
 49 
 50     /**
 51      * 獲取操作系統默認語言
 52      * 
 53      * @return String
 54      * @see java虛擬機啟動默認的編碼(一般和java文件設置格式一致)<br>
 55      *      System.out.println(Charset.defaultCharset());<br>
 56      *      查看預置的變量信息:System.getProperties().list(System.out);<br>
 57      *      屬性:<br>
 58      *      文件編碼:file.encoding<br>
 59      *      系統默認編碼sun.jnu.encoding
 60      */
 61     private static String getsystemLanguage() {
 62         return null == System.getProperty("sun.jnu.encoding") ? DEFAULT_LANGUAGE
 63                 : System.getProperty("sun.jnu.encoding");
 64     }
 65 
 66     /**
 67      * 執行cmd指令
 68      * @param cmd 執行指令
 69      */
 70     public static void executeCmd(String cmd) {
 71         executeLink(DEFAULT_LANGUAGE_CODE, true, cmd);
 72     }
 73 
 74     /**
 75      * cmd手工輸入交互處理窗口
 76      */
 77     public static void executeLink() {
 78         executeLink(DEFAULT_LANGUAGE_CODE, false, "");
 79     }
 80 
 81     /**
 82      * cmd交互處理窗口
 83      * 
 84      * @param languageCode 系統語言編碼
 85      * @param isOneRun 只執行cmd指令
 86      * @param cmd 執行的指令
 87      * @see 在中文windows系統中,根據編碼需要設置編碼 chcp 65001 就是換成UTF-8代碼頁<br>
 88      *      chcp 936 可以換回默認的GBK<br>
 89      *      chcp 437 是美國英語 <br>
 90      */
 91     public static void executeLink(String languageCode, boolean isOneRun, String cmd) {
 92         try {
 93             String cmdBin = "cmd";
 94             if (isOneRun) {
 95                 cmdBin = "cmd /c ";
 96             }
 97             Process process = Runtime.getRuntime().exec(cmdBin + cmd);
 98             PrintWriter writer = new PrintWriter(process.getOutputStream());
 99             if (!isOneRun) {
100                  // 此處可以預置交互指令
101                  // writer.println("chcp " + languageCode);
102                  writer.println("echo Hello World.");
103                  writer.flush();
104             }
105             CommandThread commandThread = new CommandThread(writer);
106             commandThread.setName("ExecuteCmdThread");
107             commandThread.start();
108             ProcessInputStreamThread inputThread = new ProcessInputStreamThread(process.getInputStream());
109             ProcessInputStreamThread errorThread = new ProcessInputStreamThread(process.getErrorStream());
110             inputThread.setName("InputStreamThread");
111             inputThread.start();
112             errorThread.setName("ErrorStreamThread");
113             errorThread.start();
114             // 即使添加下邊的一句也不會使線程結束
115             // Thread.currentThread().interrupt();
116         } catch (Exception e) {
117             e.printStackTrace();
118         }
119     }
120 
121     static class CommandThread extends Thread {
122         PrintWriter writer;
123         BufferedReader br = null;
124 
125         CommandThread(PrintWriter writer) {
126             this.writer = writer;
127             // 避免出現亂碼問題,直接使用系統默認的編碼格式
128             br = new BufferedReader(new InputStreamReader(System.in, Charset.forName(getsystemLanguage())));
129             this.setDaemon(true);
130         }
131 
132         @Override
133         public void run() {
134             try {
135                 String cmd = null;
136                 while ((cmd = br.readLine()) != null) {
137                     writer.println(cmd);
138                     writer.flush();
139                 }
140             } catch (IOException e) {
141                 e.printStackTrace();
142             } finally {
143                 if (null != writer) {
144                     writer.close();
145                 }
146                 if (null != br) {
147                     try {
148                         br.close();
149                     } catch (IOException e) {
150                         // TODO Auto-generated catch block
151                         e.printStackTrace();
152                     }
153                 }
154             }
155         }
156     }
157 
158     static class ProcessInputStreamThread extends Thread {
159 
160         InputStream input;
161         BufferedReader breader = null;
162 
163         ProcessInputStreamThread(InputStream input) {
164             this.input = input;
165             // 避免出現亂碼問題,直接使用系統默認的編碼格式
166             breader = new BufferedReader(new InputStreamReader(input, Charset.forName(getsystemLanguage())));
167         }
168 
169         @Override
170         public void run() {
171             try {
172                 String str = null;
173                 while ((str = breader.readLine()) != null) {
174                     System.out.println(str);
175                 }
176             } catch (IOException e) {
177                 e.printStackTrace();
178             } finally {
179                 if (null != input) {
180                     try {
181                         input.close();
182                     } catch (IOException e) {
183                         // TODO Auto-generated catch block
184                         e.printStackTrace();
185                     }
186                 }
187                 if (null != breader) {
188                     try {
189                         breader.close();
190                     } catch (IOException e) {
191                         // TODO Auto-generated catch block
192                         e.printStackTrace();
193                     }
194                 }
195             }
196         }
197     }
198 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM