標籤:cmd
郭嘉
郵箱:[email protected]
部落格:http://blog.csdn.net/allenwells
github:https://github.com/AllenWell
一 Java執行CMD命令
原理:
Process process = Runtime.getRuntime().exec("cmd order");
- cmd /c cmdorder 是執行完cmdorder命令後關閉命令視窗。
- cmd /k cmdorder 是執行完cmdorder命令後不關閉命令視窗。
- cmd /c start cmdorder 會開啟一個新視窗後執行cmdorder指令,原視窗會關閉。
- cmd /k start cmdorder 會開啟一個新視窗後執行cmdorder指令,原視窗不會關閉。
注意:
如果exec()中只有CMD命令,則命令會直接被執行,而不會開啟命令列視窗;
舉例:
下面例子實現了執行解壓JAR包,並把命令列資訊輸到Java的圖形介面的功能:
Process process = null;try{ process = Runtime.getRuntime().exec("jar xvf " + jarInputFile.getPath()) ;}catch (IOException e){ e.printStackTrace();}InputStream inputStream = process.getInputStream();Reader reader = new InputStreamReader(inputStream);BufferedReader bufferedReader = new BufferedReader(reader);try{ for(String s = ""; ( s = bufferedReader.readLine()) != null;) { consoleInfo.append(s + "<br>"); } bufferedReader.close(); reader.close(); JLabel consoleLabel = new JLabel(); consoleLabel.setText("<html>" + consoleInfo.toString() + "</html>"); }}catch (/ e){ e.printStackTrace();}
注意:Java Swing的文字顯示不支援直接“\n”換行,所以使用“”標籤的形式來實現換行。
二 CMD輸出資訊重新導向
以上程式展示的是把執行一條命令後,把命令列上的資訊輸出到Java的圖形介面上,那麼如何?即時的檢測Windows的命令列列印資訊並進行輸出呢?
實現方法:
Java的System類中有個out成員變數,稱為標準輸出資料流,用來把列印輸出到螢幕上。上面所述的問題其實就是System.out的輸出重新導向問題。
System.out在Java中源碼實現如下所示:
/** * Default input stream. */ public static final InputStream in; /** * Default output stream. */ public static final PrintStream out; /** * Default error output stream. */ public static final PrintStream err; private static final String lineSeparator; private static Properties systemProperties; static { err = new PrintStream(new FileOutputStream(FileDescriptor.err)); out = new PrintStream(new FileOutputStream(FileDescriptor.out)); in = new BufferedInputStream(new FileInputStream(FileDescriptor.in)); lineSeparator = System.getProperty("line.separator"); }
從上面可以看出,System.out是一個PrintStream。只需要把它重新導向到我們需要的地方就可以了,具體代碼實現如下所示:
package com.allenwells.ui;import java.awt.Color;import java.awt.Dimension;import java.io.OutputStream;import java.io.PrintStream;import javax.swing.JScrollPane;import javax.swing.JTextPane;import javax.swing.SwingUtilities;import javax.swing.text.AbstractDocument;import javax.swing.text.BadLocationException;import javax.swing.text.Document;import javax.swing.text.Element;import javax.swing.text.Style;import javax.swing.text.StyleConstants;import javax.swing.text.StyledDocument;public class ConsolePane extends JScrollPane{ private static final long serialVersionUID = 1L; private JTextPane textPane = new JTextPane(); private static ConsolePane console = null; public static synchronized ConsolePane getInstance() { if (console == null) { console = new ConsolePane(); } return console; } private ConsolePane() { setViewportView(textPane); // Set up System.out PrintStream mySystemOut = new MyPrintStream(System.out, Color.black); System.setOut(mySystemOut); // Set up System.err PrintStream mySystemErr = new MyPrintStream(System.err, Color.red); System.setErr(mySystemErr); textPane.setEditable(true); setPreferredSize(new Dimension(640, 120)); } /** * Returns the number of lines in the document. */ private final int getLineCount() { return textPane.getDocument().getDefaultRootElement().getElementCount(); } /** * Returns the start offset of the specified line. * * @param line * The line * @return The start offset of the specified line, or -1 if the line is * invalid */ private int getLineStartOffset(int line) { Element lineElement = textPane.getDocument().getDefaultRootElement() .getElement(line); if (lineElement == null) return -1; else return lineElement.getStartOffset(); } /** * 清除超過行數時前面多出行的字元 */ private void replaceRange(String str, int start, int end) { if (end < start) { throw new IllegalArgumentException("end before start"); } Document doc = textPane.getDocument(); if (doc != null) { try { if (doc instanceof AbstractDocument) { ((AbstractDocument) doc).replace(start, end - start, str, null); } else { doc.remove(start, end - start); doc.insertString(start, str, null); } } catch (BadLocationException e) { throw new IllegalArgumentException(e.getMessage()); } } } class MyPrintStream extends PrintStream { private Color foreground; // 輸出時所用字型顏色 /** * 構造自己的 PrintStream * * @param out * 可傳入 System.out 或 System.err, 實際不起作用 * @param foreground * 顯示字型顏色 */ MyPrintStream(OutputStream out, Color foreground) { super(out, true); // 使用自動重新整理 this.foreground = foreground; } /** * 在這裡重截,所有的列印方法都要調用最底一層的方法 */ public void write(byte[] buf, int off, int len) { final String message = new String(buf, off, len); /** SWING非介面線程訪問組件的方式 */ SwingUtilities.invokeLater(new Runnable() { public void run() { try { StyledDocument doc = (StyledDocument) textPane .getDocument(); // Create a style object and then set the style // attributes Style style = doc.addStyle("StyleName", null); // Foreground color StyleConstants.setForeground(style, foreground); doc.insertString(doc.getLength(), message, style); } catch (BadLocationException e) { // e.printStackTrace(); } // Make sure the last line is always visible textPane.setCaretPosition(textPane.getDocument() .getLength()); // Keep the text area down to a certain line count int idealLine = 150; int maxExcess = 50; int excess = getLineCount() - idealLine; if (excess >= maxExcess) { replaceRange("", 0, getLineStartOffset(excess)); } } }); } }}
使用方法
JPanel contentPanel = new JPanel();ConsolePane consolePane = ConsolePane.getInstance();contentPanel.add(consolePane);
如下所示:
附錄:
這裡給出常見的CMD命令:
- gpedit.msc—–組策略
- sndrec32——-錄音機
- Nslookup——-IP地址偵測器
- explorer——-開啟資源管理員
- logoff———登出命令
- tsshutdn——-60秒倒計時關機命令
- lusrmgr.msc—-本機使用者和組
- services.msc—本地服務設定
- oobe/msoobe /a—-檢查XP是否啟用
- notepad——–開啟記事本
- cleanmgr——-垃圾整理
- net start messenger—-開始信差服務
- compmgmt.msc—電腦管理
- net stop messenger—–停止信差服務
- conf———–啟動netmeeting
- dvdplay——–DVD播放器
- charmap——–啟動字元對應表
- diskmgmt.msc—磁碟管理公用程式
- calc———–啟動計算機
- dfrg.msc——-磁碟磁碟重組程式
- chkdsk.exe—–Chkdsk磁碟檢查
- devmgmt.msc— 裝置管理員
- regsvr32 /u *.dll—-停止dll檔案運行
- drwtsn32—— 系統醫生
- rononce -p —-15秒關機
- dxdiag———檢查DirectX資訊
- regedt32——-登錄編輯程式
- Msconfig.exe—系統配置公用程式
- rsop.msc——-組策略結果集
- mem.exe——–顯示記憶體使用量情況
- regedit.exe—-註冊表
- winchat——–XP內建區域網路聊天
- progman——–程式管理器
- winmsd———系統資訊
- perfmon.msc—-電腦效能監測程式
- winver———檢查Windows版本
- sfc /scannow—–掃描錯誤並複原
- taskmgr—–工作管理員(2000/xp/2003
- winver———檢查Windows版本
- wmimgmt.msc—-開啟windows管理體繫結構(WMI)
- wupdmgr——–windows更新程式
- wscript——–windows指令碼宿主設定
- write———-寫字板
- winmsd———系統資訊
- wiaacmgr——-掃描器和照相機嚮導
- winchat——–XP內建區域網路聊天
- mem.exe——–顯示記憶體使用量情況
- Msconfig.exe—系統配置公用程式
- mplayer2——-簡易widnows media player
- mspaint——–畫圖板
- mstsc———-遠端桌面連線
- mplayer2——-媒體播放機
- magnify——–放大鏡公用程式
- mmc————開啟控制台
- mobsync——–同步命令
- dxdiag———檢查DirectX資訊
- drwtsn32—— 系統醫生
- devmgmt.msc— 裝置管理員
- dfrg.msc——-磁碟磁碟重組程式
- diskmgmt.msc—磁碟管理公用程式
- dcomcnfg——-開啟系統元件服務
- ddeshare——-開啟DDE共用設定
- dvdplay——–DVD播放器
- net stop messenger—–停止信差服務
- net start messenger—-開始信差服務
- notepad——–開啟記事本
- nslookup——-網路管理的工具嚮導
- ntbackup——-系統備份與還原
- narrator——-螢幕”講述人”
- ntmsmgr.msc—-移動儲存管理器
- ntmsoprq.msc—移動儲存管理員操作請求
- netstat -an—-(TC)命令檢查介面
- syncapp——–建立一個公事包
- sysedit——–系統配置編輯器
- sigverif——-檔案簽名驗證程式
- sndrec32——-錄音機
- shrpubw——–建立共用資料夾
- secpol.msc—–本地安全性原則
- syskey———系統加密,一旦加密就不能解開,保護windows xp系統的雙重密碼
- services.msc—本地服務設定
- Sndvol32——-音量控製程序
- sfc.exe——–系統檔案檢查器
- sfc /scannow—windows檔案保護
- tsshutdn——-60秒倒計時關機命令
- tsshutdn——-60秒倒計時關機命令
- tourstart——xp簡介(安裝完成後出現的漫遊xp程式)
- taskmgr——–工作管理員
- eventvwr——-事件檢視器
- eudcedit——-造字程式
- explorer——-開啟資源管理員
- packager——-對象封裝程式
- perfmon.msc—-電腦效能監測程式
- progman——–程式管理器
- regedit.exe—-註冊表
- rsop.msc——-組策略結果集
- regedt32——-登錄編輯程式
- rononce -p —-15秒關機
- regsvr32 /u *.dll—-停止dll檔案運行
- regsvr32 /u zipfldr.dll——取消ZIP支援
- cmd.exe——–CMD命令提示字元
- chkdsk.exe—–Chkdsk磁碟檢查
- certmgr.msc—-認證管理公用程式
- calc———–啟動計算機
- charmap——–啟動字元對應表
- cliconfg——-SQL SERVER 用戶端網路公用程式
- Clipbrd——–剪貼簿查看器
- conf———–啟動netmeeting
- compmgmt.msc—電腦管理
- cleanmgr——-垃圾整理
- ciadv.msc——索引服務程式
- osk————開啟螢幕小鍵盤
- odbcad32——-ODBC資料來源管理器
- oobe/msoobe /a—-檢查XP是否啟用
- lusrmgr.msc—-本機使用者和組
- logoff———登出命令
- iexpress——-木馬捆綁工具,系統內建
- Nslookup——-IP地址偵測器
- fsmgmt.msc—–共用資料夾管理器
- utilman——–協助工具輔助管理器
- gpedit.msc—–組策略
著作權聲明:本文為博主原創文章,未經博主允許不得轉載。
【Java基礎】Java與Windows系統的互動