Java operation Linux, invoke shell command

Source: Internet
Author: User
Tags call shell dateformat stringbuffer

Importorg.junit.jupiter.api.Test;ImportJava.io.BufferedReader;Importjava.io.IOException;ImportJava.io.InputStreamReader;ImportJava.io.OutputStreamWriter;ImportJava.io.PrintWriter;ImportJava.util.logging.Level;ImportJava.util.logging.Logger; Public classTest001 { Public StaticString exec (String command)throwsinterruptedexception {String returnstring= ""; Process Pro=NULL; Runtime Runtime=Runtime.getruntime (); if(RunTime = =NULL) {System.err.println ("Create Runtime false!"); }        Try{Pro=runtime.exec (command); BufferedReader input=NewBufferedReader (NewInputStreamReader (Pro.getinputstream ())); PrintWriter Output=NewPrintWriter (NewOutputStreamWriter (Pro.getoutputstream ()));            String Line;  while(line = Input.readline ())! =NULL) {returnstring= returnstring + line + "\ n";            } input.close ();            Output.close ();        Pro.destroy (); } Catch(IOException ex) {Logger.getlogger (Test001.class. GetName ()). log (Level.severe,NULL, ex); }        returnreturnstring; } @Test Public voidTest ()throwsException {System.out.println (EXEC ("Ls-al")); }}

MAC also works

Call the shell script to determine if the normal execution, if the normal end, the process of the WAITFOR () method returns 0

 Public Static void Callshell (String shellstring) {      try  {          = runtime.getruntime (). EXEC ( shellstring);           int exitvalue = process.waitfor ();           if (0! = exitvalue) {              log.error ("Call shell failed. Error code is:" + exitvalue);          }       Catch (Throwable e) {          log.error ("Call Shell failed. "+ e);      }  }

 PackageTest.shell;ImportJava.io.BufferedReader;ImportJava.io.FileOutputStream;Importjava.io.IOException;ImportJava.io.OutputStream;ImportJava.io.OutputStreamWriter;ImportJava.text.DateFormat;ImportJava.text.SimpleDateFormat;Importjava.util.Date; Public classJavashellutil {//Basic Path    Private Static FinalString basepath = "/tmp/"; //location of log files that record shell execution (absolute path)    Private Static FinalString executeshelllogfile = basepath + "ExecuteShell.log"; //The file name (absolute path) of the shell that sent the file to the Kondor system    Private Static FinalString sendkondorshellname = basepath + "sendkondorfile.sh";  Public intExecuteshell (String Shellcommand)throwsIOException {intSuccess = 0; StringBuffer StringBuffer=NewStringBuffer (); BufferedReader BufferedReader=NULL;//format Date time, use when loggingDateFormat DateFormat =NewSimpleDateFormat ("Yyyy-mm-dd HH:mm:SS"); Try{stringbuffer.append (Dateformat.format (NewDate ()). Append ("Prepare to execute Shell command"). Append (Shellcommand). Append ("\ r \ n"); Process PID=NULL; string[] cmd= {"/bin/sh", "-C", Shellcommand}; //Execute shell CommandPID =runtime.getruntime (). exec (CMD); if(PID! =NULL) {stringbuffer.append ("Process number:"). Append (Pid.tostring ()). Append ("\ r \ n"); //The BufferedReader is used to read the Shell's output BufferedReader = new BufferedReader (New InputStreamReader (Pid.getinputstream ()), (1024x768);pid.waitfor (); } Else{stringbuffer.append ("No pid\r\n"); } stringbuffer.append (Dateformat.format (NewDate ())). Append ("The shell command has been executed \ r \ n The result is: \ r \ n"); String Line=NULL; //reads the output from the shell and adds it to the StringBuffer             while(BufferedReader! =NULL&& (line = Bufferedreader.readline ())! =NULL) {stringbuffer.append (line). Append ("\ r \ n"); }        } Catch(Exception IoE) {stringbuffer.append ("Exception occurred executing shell command: \ r \ n"). Append (Ioe.getmessage ()). Append ("\ r \ n").); } finally {            if(BufferedReader! =NULL) {OutputStreamWriter OutputStreamWriter=NULL; Try{bufferedreader.close (); //output the execution of the shell to a log fileOutputStream OutputStream =NewFileOutputStream (Executeshelllogfile); OutputStreamWriter=NewOutputStreamWriter (OutputStream, "UTF-8");                Outputstreamwriter.write (Stringbuffer.tostring ()); } Catch(Exception e) {e.printstacktrace (); } finally{outputstreamwriter.close (); }} Success= 1; }        returnsuccess; }}  

More information:

Http://www.cnblogs.com/shihaiming/p/5884859.html

Http://www.jb51.net/article/69930.htm

Java Operations Linux, invoking shell commands

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.