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:
- gpedit.msc-– Group Policy
- Sndrec32 ——-Recorder
- Nslookup ——-IP Address detector
- Explorer ——-Open Resource Manager
- Logoff ——— Logoff command
- Tsshutdn ——-60-second Countdown shutdown command
- lusrmgr.msc--Native Users and Groups
- services.msc-Local Service settings
- oobe/msoobe/a--Check if XP is active
- notepad--– Open Notepad
- cleanmgr ——-Waste Finishing
- net start messenger--Messenger Service
- compmgmt.msc-Computer Management
- net stop messenger-– stop messenger Service
- Conf ——— – Start NetMeeting
- Dvdplay--–dvd player
- charmap--– Startup character Mapping table
- diskmgmt.msc-Disk Management Utility
- Calc ——— – Start Calculator
- Dfrg.msc ——-Disk Defragmenter
- Chkdsk.exe-–chkdsk disk Check
- devmgmt.msc-Device Manager
- regsvr32/u *.dll--Stop DLL file run
- drwtsn32--System Doctor
- rononce-p--15 seconds shutdown
- DxDiag ——— checking DirectX information
- Regedt32 ——-Registry Editor
- msconfig.exe-System Configuration Utility
- Rsop.msc ——-Group Policy result set
- mem.exe--– Display Memory usage
- regedit.exe--Registration Form
- WINCHAT--–XP self-brought LAN chat
- progman--– Program Manager
- WINMSD ——— System Information
- perfmon.msc--Computer Performance Monitoring Program
- Winver ——— Check the Windows version
- sfc/scannow-– Scan error and restore
- taskmgr-– Task Manager (2000/xp/2003
- Winver ——— Check the Windows version
- wmimgmt.msc--Opening Windows Management Architecture (WMI)
- Wupdmgr--–windows Update Program
- Wscript--–windows Script Host Settings
- Write ———-WordPad
- WINMSD ——— System Information
- Wiaacmgr ——-Scanner and Camera Wizard
- WINCHAT--–XP self-brought LAN chat
- mem.exe--– Display Memory usage
- msconfig.exe-System Configuration Utility
- Mplayer2 ——-Easy widnows Media Player
- mspaint--– drawing board
- MSTSC ———-Remote Desktop Connection
- Mplayer2 ——-Media Player
- magnify--– Magnifier Utility
- MMC ———— Open the console
- mobsync--– Synchronization Command
- DxDiag ——— checking DirectX information
- drwtsn32--System Doctor
- devmgmt.msc-Device Manager
- Dfrg.msc ——-Disk Defragmenter
- diskmgmt.msc-Disk Management Utility
- DCOMCNFG ——-Open System Component Services
- DdeShare ——-turn on DDE sharing settings
- Dvdplay--–dvd player
- net stop messenger-– stop messenger Service
- net start messenger--Messenger Service
- notepad--– Open Notepad
- Nslookup Tool Wizard for ——-network management
- Ntbackup ——-system backup and restore
- Narrator ——-Screen Narrator
- ntmsmgr.msc--Mobile Storage Manager
- ntmsoprq.msc-Mobile Storage Administrator Action Request
- netstat-an--(TC) command Check interface
- syncapp--– Create a Briefcase
- sysedit--– System Configuration Editor
- Sigverif ——-File Signature Validator
- Sndrec32 ——-Recorder
- shrpubw--– Creating a shared folder
- secpol.msc-– Local Security Policy
- Syskey ——— system encryption, once encrypted can not be solved, protect the Windows XP system dual Password
- services.msc-Local Service settings
- Sndvol32 ——-Volume Control program
- sfc.exe--– System File Checker
- Sfc/scannow-windows File Protection
- Tsshutdn ——-60-second Countdown shutdown command
- Tsshutdn ——-60-second Countdown shutdown command
- TOURSTART--XP profile (roaming XP programs that appear after installation is complete)
- taskmgr--– Task Manager
- EVENTVWR ——-Event Viewer
- Eudcedit ——-Character-font procedure
- Explorer ——-Open Resource Manager
- Packager ——-Object Wrapping Program
- perfmon.msc--Computer Performance Monitoring Program
- progman--– Program Manager
- regedit.exe--Registration Form
- Rsop.msc ——-Group Policy result set
- Regedt32 ——-Registry Editor
- rononce-p--15 seconds shutdown
- regsvr32/u *.dll--Stop DLL file run
- regsvr32/u zipfldr.dll--Cancel Zip support
- Cmd.exe--–cmd Command Prompt
- Chkdsk.exe-–chkdsk disk Check
- certmgr.msc--Certificate Management Utility
- Calc ——— – Start Calculator
- charmap--– Startup character Mapping table
- CLICONFG ——-SQL SERVER Client Network Utility
- clipbrd--– Clipboard Viewer
- Conf ——— – Start NetMeeting
- compmgmt.msc-Computer Management
- cleanmgr ——-Waste Finishing
- ciadv.msc--Indexing Service Program
- OSK ———— Open the On-screen keyboard
- ODBCAD32 ——-ODBC data Source Manager
- oobe/msoobe/a--Check if XP is active
- lusrmgr.msc--Native Users and Groups
- Logoff ——— Logoff command
- IExpress ——-Trojan Bundle tool, System comes with
- Nslookup ——-IP Address detector
- fsmgmt.msc-– shared Folder Manager
- utilman--– Utility Manager
- 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