【Java基礎】Java與Windows系統的互動

來源:互聯網
上載者:User

標籤: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命令:

  1. gpedit.msc—–組策略
  2. sndrec32——-錄音機
  3. Nslookup——-IP地址偵測器
  4. explorer——-開啟資源管理員
  5. logoff———登出命令
  6. tsshutdn——-60秒倒計時關機命令
  7. lusrmgr.msc—-本機使用者和組
  8. services.msc—本地服務設定
  9. oobe/msoobe /a—-檢查XP是否啟用
  10. notepad——–開啟記事本
  11. cleanmgr——-垃圾整理
  12. net start messenger—-開始信差服務
  13. compmgmt.msc—電腦管理
  14. net stop messenger—–停止信差服務
  15. conf———–啟動netmeeting
  16. dvdplay——–DVD播放器
  17. charmap——–啟動字元對應表
  18. diskmgmt.msc—磁碟管理公用程式
  19. calc———–啟動計算機
  20. dfrg.msc——-磁碟磁碟重組程式
  21. chkdsk.exe—–Chkdsk磁碟檢查
  22. devmgmt.msc— 裝置管理員
  23. regsvr32 /u *.dll—-停止dll檔案運行
  24. drwtsn32—— 系統醫生
  25. rononce -p —-15秒關機
  26. dxdiag———檢查DirectX資訊
  27. regedt32——-登錄編輯程式
  28. Msconfig.exe—系統配置公用程式
  29. rsop.msc——-組策略結果集
  30. mem.exe——–顯示記憶體使用量情況
  31. regedit.exe—-註冊表
  32. winchat——–XP內建區域網路聊天
  33. progman——–程式管理器
  34. winmsd———系統資訊
  35. perfmon.msc—-電腦效能監測程式
  36. winver———檢查Windows版本
  37. sfc /scannow—–掃描錯誤並複原
  38. taskmgr—–工作管理員(2000/xp/2003
  39. winver———檢查Windows版本
  40. wmimgmt.msc—-開啟windows管理體繫結構(WMI)
  41. wupdmgr——–windows更新程式
  42. wscript——–windows指令碼宿主設定
  43. write———-寫字板
  44. winmsd———系統資訊
  45. wiaacmgr——-掃描器和照相機嚮導
  46. winchat——–XP內建區域網路聊天
  47. mem.exe——–顯示記憶體使用量情況
  48. Msconfig.exe—系統配置公用程式
  49. mplayer2——-簡易widnows media player
  50. mspaint——–畫圖板
  51. mstsc———-遠端桌面連線
  52. mplayer2——-媒體播放機
  53. magnify——–放大鏡公用程式
  54. mmc————開啟控制台
  55. mobsync——–同步命令
  56. dxdiag———檢查DirectX資訊
  57. drwtsn32—— 系統醫生
  58. devmgmt.msc— 裝置管理員
  59. dfrg.msc——-磁碟磁碟重組程式
  60. diskmgmt.msc—磁碟管理公用程式
  61. dcomcnfg——-開啟系統元件服務
  62. ddeshare——-開啟DDE共用設定
  63. dvdplay——–DVD播放器
  64. net stop messenger—–停止信差服務
  65. net start messenger—-開始信差服務
  66. notepad——–開啟記事本
  67. nslookup——-網路管理的工具嚮導
  68. ntbackup——-系統備份與還原
  69. narrator——-螢幕”講述人”
  70. ntmsmgr.msc—-移動儲存管理器
  71. ntmsoprq.msc—移動儲存管理員操作請求
  72. netstat -an—-(TC)命令檢查介面
  73. syncapp——–建立一個公事包
  74. sysedit——–系統配置編輯器
  75. sigverif——-檔案簽名驗證程式
  76. sndrec32——-錄音機
  77. shrpubw——–建立共用資料夾
  78. secpol.msc—–本地安全性原則
  79. syskey———系統加密,一旦加密就不能解開,保護windows xp系統的雙重密碼
  80. services.msc—本地服務設定
  81. Sndvol32——-音量控製程序
  82. sfc.exe——–系統檔案檢查器
  83. sfc /scannow—windows檔案保護
  84. tsshutdn——-60秒倒計時關機命令
  85. tsshutdn——-60秒倒計時關機命令
  86. tourstart——xp簡介(安裝完成後出現的漫遊xp程式)
  87. taskmgr——–工作管理員
  88. eventvwr——-事件檢視器
  89. eudcedit——-造字程式
  90. explorer——-開啟資源管理員
  91. packager——-對象封裝程式
  92. perfmon.msc—-電腦效能監測程式
  93. progman——–程式管理器
  94. regedit.exe—-註冊表
  95. rsop.msc——-組策略結果集
  96. regedt32——-登錄編輯程式
  97. rononce -p —-15秒關機
  98. regsvr32 /u *.dll—-停止dll檔案運行
  99. regsvr32 /u zipfldr.dll——取消ZIP支援
  100. cmd.exe——–CMD命令提示字元
  101. chkdsk.exe—–Chkdsk磁碟檢查
  102. certmgr.msc—-認證管理公用程式
  103. calc———–啟動計算機
  104. charmap——–啟動字元對應表
  105. cliconfg——-SQL SERVER 用戶端網路公用程式
  106. Clipbrd——–剪貼簿查看器
  107. conf———–啟動netmeeting
  108. compmgmt.msc—電腦管理
  109. cleanmgr——-垃圾整理
  110. ciadv.msc——索引服務程式
  111. osk————開啟螢幕小鍵盤
  112. odbcad32——-ODBC資料來源管理器
  113. oobe/msoobe /a—-檢查XP是否啟用
  114. lusrmgr.msc—-本機使用者和組
  115. logoff———登出命令
  116. iexpress——-木馬捆綁工具,系統內建
  117. Nslookup——-IP地址偵測器
  118. fsmgmt.msc—–共用資料夾管理器
  119. utilman——–協助工具輔助管理器
  120. gpedit.msc—–組策略

著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

【Java基礎】Java與Windows系統的互動

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.