Java Execution Cmd/dos

Source: Internet
Author: User

Recently in writing a own mailbox server to use

Monitor and start/stop services in Windows, and the investigation finds that DOS is the way to do it.

Talk about the skirmish process.

The first is how to execute DOS command in Java, check the following function

Runtime.getruntime (). EXEC ()

(Here you can try to start a notepad calculator with Runtime.getruntime (). ("Notepad"); Runtime.getruntime (). ("Calc"); )

And then the DOS command is ready.

Service start SC start "service name"

Service Stop SC start "service name"

Service Status SC query "service name"

(quotation marks must be)

Then there is the question of the return value of the start/Stop command followed by a return value.

Haven't found a better solution now basically is to print in the cmd box in a row of the output of their own judgment

1 PrivateMap<string, string>executecmd (String cmd) {2Runtime RT = Runtime.getruntime ();//run-time system acquisition3map<string, string> linemap =NewHashmap<string, string> ();//Store return value4         Try {5Process proc = rt.exec (cmd);//Execute Command6InputStream stderr = Proc.getinputstream ();//the standard output flow of the process is obtained by executing the result7InputStreamReader ISR =NewInputStreamReader (stderr);//Convert a byte stream into a character stream8BufferedReader br =NewBufferedReader (ISR);//output a stream of characters in a row in a cached form9String line =NULL;Ten              while(line = Br.readline ())! =NULL) {  One                 if(!Stringutils.isempty (line)) { Astring[] StrLine = Line.split (":"); -                     if(strline.length>=2) { -Linemap.put (Strline[0].trim (), strline[1].trim ()); the                     } -                      -                 } -             } + br.close (); - isr.close (); + stderr.close (); A}Catch(IOException e) { at e.printstacktrace (); -         } -         returnLinemap; -}

PS:L11-17 depending on the execution results of the different commands. I got the xx:yy here, so that's the deal.

Next is how the bat file is located

The same way to change the command to your bat path is good, this is not much to say a question about permissions

BAT file If the permissions are not sufficient typically the mail bat file is run as an administrator and this process

But how do you deal with it in Java? As follows

1 @echo off2Mode con lines= -cols= -3%1Mshta Vbscript:createobject ("shell.application"). ShellExecute ("Cmd.exe","/ C%~s0::","","runas",1) (Window.close) &&Exit4cd/d"%~dp0"5Rem

And then add the bat command you're going to write.

Now think about it suddenly feels horrible to have Admin permissions can also write your own cmd create shell execution ...

And one is to look at the Internet. The basic solution is multithreading because there are too many commands or too many things to do.

Is that the output stream (getInputStream) and error Stream (Getoutputstream) of the processing process are assigned to two threads to do the following

 Public classStreammanageextendsThread {Private FinalLogger Logger = Loggerfactory.getlogger ( This. GetClass ());    InputStream InputStream;    String type;  Publicstreammanage (InputStream inputstream,string type) { This. InputStream =InputStream;  This. Type =type; }     Public voidrun () {InputStreamReader InputStreamReader=NewInputStreamReader (InputStream); BufferedReader BufferedReader=NewBufferedReader (InputStreamReader); String Line=NULL; Try {             while(line = Bufferedreader.readline ())! =NULL ) {                if(Type.equals ("Error") {logger.error (line); }Else{logger.debug (line); }            }        } Catch(IOException e) {e.printstacktrace (); }    }}

There should be nothing to say here is to pass the output stream through to do the output processing, and then call the place

l8,9

1     Private voidStartmailserver () {2String cmd = "sc start \" James 2.3.2.1\ ";//DOS command3Runtime RT = Runtime.getruntime ();//run-time system acquisition4         Try {5             //Process proc = rt.exec (cmd);//Execute Command6File FilePath =NewFile ("Src\\main\\resources\\static\\bat\\runstart.bat");7Process proc =rt.exec (filepath.tostring ());8Streammanage Errorstream =NewStreammanage (Proc.geterrorstream (), "Error");9Streammanage OutputStream =NewStreammanage (Proc.getinputstream (), "Output");Ten Errorstream.start (); One Outputstream.start (); A}Catch(IOException e) { - e.printstacktrace (); -         } the}

That's basically it.

Finally, a residue problem.

Is the cmd window splash screen problem if the execution of the command this problem does not exist if the bat is not to get Admin permissions This problem also did not guess on the code to get permission to create a splash screen survey ... If you know anything, please tell me.

Java Execution Cmd/dos

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.