1 Public classStreamgobblerextendsThread {2 3 InputStream is; 4 String type; 5 6 PublicStreamgobbler (InputStream is, String type) {7 This. is =is ; 8 This. Type =type; 9 } Ten One Public voidrun () { A Try { -InputStreamReader ISR =NewInputStreamReader (IS); -BufferedReader br =NewBufferedReader (ISR); theString line =NULL; - while(line = Br.readline ())! =NULL) { - if(Type.equals ("Error")) { -System.out.println ("Error:" +Line ); +}Else { -System.out.println ("Debug:" +Line ); + } A } at}Catch(IOException IoE) { - Ioe.printstacktrace (); - } - } -}
1 Private voidShell (String cmd)2 {3String[] Cmds = {"/bin/sh", "-C", cmd};4 process process;5 6 Try7 {8Process =runtime.getruntime (). exec (CMDS);9 TenStreamgobbler Errorgobbler =NewStreamgobbler (Process.geterrorstream (), "Error"); OneStreamgobbler Outputgobbler =NewStreamgobbler (Process.getinputstream (), "Output"); A Errorgobbler.start (); - Outputgobbler.start (); - Try the { - process.waitfor (); - } - Catch(interruptedexception e) + { - e.printstacktrace (); + } A } at Catch(IOException e) - { - e.printstacktrace (); - } -}
The parameter cmd is the Linux command. Only one command can be executed at a time.
- Java runtime.exec () Considerations
- Always read the data stream before calling the WAITFOR () method
- Always read from the standard error stream before reading the standard output stream
2. The best way to execute a system command is to write a bat file or a shell script.
Resources:
Note reference:
http://blog.csdn.net/flying881114/article/details/6272472
Http://blog.csdn.net/westwin/archive/2005/04/22/358377.aspx
Http://blog.csdn.net/moreorless/archive/2009/05/15/4182883.aspx
Shell Script Reference:
Http://blog.csdn.net/HEYUTAO007/archive/2010/06/30/5705499.aspx
Java Execute Linux command