"Java Fundamentals" Java interacts with Windows systems

Source: Internet
Author: User
Tags nslookup nslookup tool disk defragmenter

Guo Jia
Email: [Email protected]
Blog: http://blog.csdn.net/allenwells
Github:https://github.com/allenwell

A Java Execute cmd command

principle :

Process process = Runtime.getRuntime().exec("cmd order");
    • CMD/C Cmdorder is the Close command window after executing the cmdorder command.
    • cmd/k cmdorder The Command window is not closed after the Cmdorder command is executed.
    • CMD/C start Cmdorder will open a new window and execute the cmdorder instruction, the original window will be closed.
    • cmd/k start Cmdorder will open a new window and execute the cmdorder instruction, the original window will not be closed.

Note :

If there is only a cmd command in exec (), the command is executed directly without opening the command-line window;

Example :

The following example implements the ability to execute an extract jar package and send command line information to the Java graphical interface:

Process Process =NULL;Try{process = Runtime.getruntime (). EXEC ("Jar XVF"+ Jarinputfile.getpath ());}Catch(IOException e) {E.printstacktrace ();} InputStream InputStream = Process.getinputstream (); Reader reader =NewInputStreamReader (InputStream); BufferedReader BufferedReader =NewBufferedReader (reader);Try{ for(String s =""; (s = bufferedreader.readline ())! =NULL;) {Consoleinfo.append (S +"<br>");        } bufferedreader.close ();        Reader.close (); JLabel Consolelabel =NewJLabel (); Consolelabel.settext ("+ consoleinfo.tostring () +"); }}Catch(/E) {E.printstacktrace ();}

Note : The text display in Java Swing does not support the direct "\ n" line wrapping, so the "" tab is used to implement line breaks.

Two cmd output information redirection

The above program shows that after executing a command, the command line information output to the Java graphical interface, then how to implement real-time detection of Windows command line printing information and output it?

Implementation Method :

The Java System class has an out member variable called the standard output stream, which is used to print output to the screen. The problem described above is actually the output redirection problem of System.out.

System.out in Java The source code implementation is as follows:

    /** * Default input stream. */     Public Static FinalInputStream in;/** * Default output stream. */     Public Static FinalPrintStream out;/** * Default error output stream. */     Public Static FinalPrintStream err;Private Static FinalString LineSeparator;Private StaticProperties systemproperties;Static{err =NewPrintStream (NewFileOutputStream (Filedescriptor.err)); out =NewPrintStream (NewFileOutputStream (filedescriptor.out)); in =NewBufferedinputstream (NewFileInputStream (filedescriptor.in)); LineSeparator = System.getproperty ("Line.separator"); }

As can be seen from the above, System.out is a printstream. Just redirect it to where we need it, and the specific code is implemented as follows:

 PackageCom.allenwells.ui;ImportJava.awt.Color;ImportJava.awt.Dimension;ImportJava.io.OutputStream;ImportJava.io.PrintStream;ImportJavax.swing.JScrollPane;ImportJavax.swing.JTextPane;ImportJavax.swing.SwingUtilities;ImportJavax.swing.text.AbstractDocument;ImportJavax.swing.text.BadLocationException;ImportJavax.swing.text.Document;ImportJavax.swing.text.Element;ImportJavax.swing.text.Style;Importjavax.swing.text.StyleConstants;ImportJavax.swing.text.StyledDocument; Public  class consolepane extends jscrollpane{    Private Static Final LongSerialversionuid =1LPrivateJtextpane TextPane =NewJtextpane ();Private StaticConsolepane console =NULL; Public Static synchronizedConsolepanegetinstance()    {if(Console = =NULL) {console =NewConsolepane (); }returnConsole }Private Consolepane() {Setviewportview (TextPane);//Set up System.outPrintStream mysystemout =NewMyprintstream (System.out, Color.Black); System.setout (mysystemout);//Set up System.errPrintStream Mysystemerr =NewMyprintstream (System.err, color.red);        System.seterr (Mysystemerr); Textpane.seteditable (true); Setpreferredsize (NewDimension (640, -)); }/** * Returns The number of lines in the document. */    Private Final int Getlinecount()    {returnTextpane.getdocument (). Getdefaultrootelement (). Getelementcount (); }/** * Returns The start offset of the specified line. * * @param Line * The line * @return The start offset by the specified line, or -1 if the line is * invalid * /    Private int Getlinestartoffset(intLine) {Element lineelement = Textpane.getdocument (). Getdefaultrootelement (). GetElement (line);if(Lineelement = =NULL)return-1;Else            returnLineelement.getstartoffset (); }/** * Clear the number of travel characters in front of more than the number of lines */    Private void Replacerange(String str,intStartintEnd) {if(End < start) {Throw NewIllegalArgumentException ("End before start"); } Document doc = Textpane.getdocument ();if(Doc! =NULL)        {Try{if(docinstanceofAbstractdocument) {((abstractdocument) doc). Replace (start, End-start, str,NULL); }Else{Doc.remove (start, End-start); Doc.insertstring (Start, str,NULL); }            }Catch(Badlocationexception e) {Throw NewIllegalArgumentException (E.getmessage ()); }}} class Myprintstream extends PrintStream {PrivateColor foreground;//The font color used for output        /** * Constructs its own printstream * * @param out * can be passed into System.out or System. Err, actually does not work * @param foreground * Display Font color */Myprintstream (OutputStream out, Color foreground) {Super(Out,true);//Use automatic refresh             This. foreground = foreground; }/** * In this section, all the printing methods to call the bottom layer of the method * /         Public void Write(byte[] buf,intOffintLen) {FinalString message =NewString (buf, off, Len);/** Swing Non-interface thread how to access Components * /Swingutilities.invokelater (NewRunnable () { Public void Run()                {Try{Styleddocument doc = (styleddocument) textPane. GetDocument ();//Create a Style object and then set the style                        //AttributesStyle style = Doc.addstyle ("StyleName",NULL);//Foreground colorStyleconstants.setforeground (style, foreground);                    Doc.insertstring (Doc.getlength (), message, style); }Catch(Badlocationexception e) {//E.printstacktrace ();}//Make sure the last line was always visibleTextpane.setcaretposition (Textpane.getdocument (). GetLength ());//Keep The text area down to a certain line count                    intIdealline = Max;intMaxexcess = -;intExcess = Getlinecount ()-idealline;if(Excess >= maxexcess) {Replacerange ("",0, Getlinestartoffset (excess));        }                }            }); }    }}

How to use

new JPanel();ConsolePane consolePane = ConsolePane.getInstance();contentPanel.add(consolePane);

As shown below:

Appendix:

Here is a common cmd command:

  1. gpedit.msc-– Group Policy
  2. Sndrec32 ——-Recorder
  3. Nslookup ——-IP Address detector
  4. Explorer ——-Open Resource Manager
  5. Logoff ——— Logoff command
  6. Tsshutdn ——-60-second Countdown shutdown command
  7. lusrmgr.msc--Native Users and Groups
  8. services.msc-Local Service settings
  9. oobe/msoobe/a--Check if XP is active
  10. notepad--– Open Notepad
  11. cleanmgr ——-Waste Finishing
  12. net start messenger--Messenger Service
  13. compmgmt.msc-Computer Management
  14. net stop messenger-– stop messenger Service
  15. Conf ——— – Start NetMeeting
  16. Dvdplay--–dvd player
  17. charmap--– Startup character Mapping table
  18. diskmgmt.msc-Disk Management Utility
  19. Calc ——— – Start Calculator
  20. Dfrg.msc ——-Disk Defragmenter
  21. Chkdsk.exe-–chkdsk disk Check
  22. devmgmt.msc-Device Manager
  23. regsvr32/u *.dll--Stop DLL file run
  24. drwtsn32--System Doctor
  25. rononce-p--15 seconds shutdown
  26. DxDiag ——— checking DirectX information
  27. Regedt32 ——-Registry Editor
  28. msconfig.exe-System Configuration Utility
  29. Rsop.msc ——-Group Policy result set
  30. mem.exe--– Display Memory usage
  31. regedit.exe--Registration Form
  32. WINCHAT--–XP self-brought LAN chat
  33. progman--– Program Manager
  34. WINMSD ——— System Information
  35. perfmon.msc--Computer Performance Monitoring Program
  36. Winver ——— Check the Windows version
  37. sfc/scannow-– Scan error and restore
  38. taskmgr-– Task Manager (2000/xp/2003
  39. Winver ——— Check the Windows version
  40. wmimgmt.msc--Opening Windows Management Architecture (WMI)
  41. Wupdmgr--–windows Update Program
  42. Wscript--–windows Script Host Settings
  43. Write ———-WordPad
  44. WINMSD ——— System Information
  45. Wiaacmgr ——-Scanner and Camera Wizard
  46. WINCHAT--–XP self-brought LAN chat
  47. mem.exe--– Display Memory usage
  48. msconfig.exe-System Configuration Utility
  49. Mplayer2 ——-Easy widnows Media Player
  50. mspaint--– drawing board
  51. MSTSC ———-Remote Desktop Connection
  52. Mplayer2 ——-Media Player
  53. magnify--– Magnifier Utility
  54. MMC ———— Open the console
  55. mobsync--– Synchronization Command
  56. DxDiag ——— checking DirectX information
  57. drwtsn32--System Doctor
  58. devmgmt.msc-Device Manager
  59. Dfrg.msc ——-Disk Defragmenter
  60. diskmgmt.msc-Disk Management Utility
  61. DCOMCNFG ——-Open System Component Services
  62. DdeShare ——-turn on DDE sharing settings
  63. Dvdplay--–dvd player
  64. net stop messenger-– stop messenger Service
  65. net start messenger--Messenger Service
  66. notepad--– Open Notepad
  67. Nslookup Tool Wizard for ——-network management
  68. Ntbackup ——-system backup and restore
  69. Narrator ——-Screen Narrator
  70. ntmsmgr.msc--Mobile Storage Manager
  71. ntmsoprq.msc-Mobile Storage Administrator Action Request
  72. netstat-an--(TC) command Check interface
  73. syncapp--– Create a Briefcase
  74. sysedit--– System Configuration Editor
  75. Sigverif ——-File Signature Validator
  76. Sndrec32 ——-Recorder
  77. shrpubw--– Creating a shared folder
  78. secpol.msc-– Local Security Policy
  79. Syskey ——— system encryption, once encrypted can not be solved, protect the Windows XP system dual Password
  80. services.msc-Local Service settings
  81. Sndvol32 ——-Volume Control program
  82. sfc.exe--– System File Checker
  83. Sfc/scannow-windows File Protection
  84. Tsshutdn ——-60-second Countdown shutdown command
  85. Tsshutdn ——-60-second Countdown shutdown command
  86. TOURSTART--XP profile (roaming XP programs that appear after installation is complete)
  87. taskmgr--– Task Manager
  88. EVENTVWR ——-Event Viewer
  89. Eudcedit ——-Character-font procedure
  90. Explorer ——-Open Resource Manager
  91. Packager ——-Object Wrapping Program
  92. perfmon.msc--Computer Performance Monitoring Program
  93. progman--– Program Manager
  94. regedit.exe--Registration Form
  95. Rsop.msc ——-Group Policy result set
  96. Regedt32 ——-Registry Editor
  97. rononce-p--15 seconds shutdown
  98. regsvr32/u *.dll--Stop DLL file run
  99. regsvr32/u zipfldr.dll--Cancel Zip support
  100. Cmd.exe--–cmd Command Prompt
  101. Chkdsk.exe-–chkdsk disk Check
  102. certmgr.msc--Certificate Management Utility
  103. Calc ——— – Start Calculator
  104. charmap--– Startup character Mapping table
  105. CLICONFG ——-SQL SERVER Client Network Utility
  106. clipbrd--– Clipboard Viewer
  107. Conf ——— – Start NetMeeting
  108. compmgmt.msc-Computer Management
  109. cleanmgr ——-Waste Finishing
  110. ciadv.msc--Indexing Service Program
  111. OSK ———— Open the On-screen keyboard
  112. ODBCAD32 ——-ODBC data Source Manager
  113. oobe/msoobe/a--Check if XP is active
  114. lusrmgr.msc--Native Users and Groups
  115. Logoff ——— Logoff command
  116. IExpress ——-Trojan Bundle tool, System comes with
  117. Nslookup ——-IP Address detector
  118. fsmgmt.msc-– shared Folder Manager
  119. utilman--– Utility Manager
  120. gpedit.msc-– Group Policy

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

"Java Fundamentals" Java interacts with Windows systems

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.