One, Java calls the Linux System command is very simple
This is a very common example of calling methods:
1 Publicstring Executelinuxcmd (string cmd) {2System. out. println ("got cmd job:"+cmd);3Runtime Run =runtime.getruntime ();4 Try {5Process Process =run.exec (cmd);6InputStreaminch=Process.getinputstream ();7BufferedReader bs =NewBufferedReader (NewInputStreamReader (inch));8 //System.out.println ("[check] now size \ n" +bs.readline ());9String result =NULL;Ten while(inch. read ()! =-1) { Oneresult =bs.readline (); ASystem. out. println ("job Result ["+ result +"]"); - } - inch. Close (); the //process.waitfor (); - Process.destroy (); - returnresult; -}Catch(IOException e) { + e.printstacktrace (); - } + return NULL; A}
Ii. examples of methods that contain CD operations
1. Issue background
1.1 Java program runs under the/home/lings directory;
1.2 Want to delete the file Proxy.log under the/home/test directory;
1.3 Call the above interface two times?
Executelinuxcmd ("cd/home/test"); Executelinuxcmd ("rm-fr/home/ Proxy.log");
It's not going to work!
1.4 The invocation of this interface is a single transaction type, that is, each call is a separate transaction or operation, there is no correlation.
What about this "complicated" operation?
1.5 Method A: You can write a separate script, and then run the script one at a time, so that many complex logic is fine.
1.6 Method B: You can start a shell long connection, keep the connection, send multiple commands, and finally release the connection.
Sample Logic code:
1 Public voidExecutenewflow () {2Runtime Run =runtime.getruntime ();3File WD =NewFile ("/bin");4System. out. println (wd);5Process proc =NULL;6 Try {7proc = run.exec ("/bin/bash",NULL, wd);8}Catch(IOException e) {9 e.printstacktrace ();Ten } One if(Proc! =NULL) { ABufferedReaderinch=NewBufferedReader (NewInputStreamReader (Proc.getinputstream ())); -PrintWriter out=NewPrintWriter (NewBufferedWriter (NewOutputStreamWriter (Proc.getoutputstream ())),true); - out. println ("cd/home/test"); the out. println ("pwd"); - out. println ("Rm-fr/home/proxy.log"); - out. println ("Exit"); - Try { + String Line; - while(line =inch. ReadLine ())! =NULL) { +System. out. println (line); A } at proc.waitfor (); - inch. Close (); - out. Close (); - Proc.destroy (); -}Catch(Exception e) { - e.printstacktrace (); in } - } to}
Java calls the Linux command (CD processing)