Java calls local commands

Source: Internet
Author: User

Reference: http://blog.csdn.net/zhu_xun/article/details/19539513

Http://www.cnblogs.com/kingcucumber/p/3180146.html

First, the Process class

Processbuilder.start () Creates a native process and returns an instance of a process subclass that can obtain information about the processes or control the process. This process does not have its own terminal, its operation result IO is redirected to its parent process, the parent process provides input and fetch output for the child process through getInputStream (), Getoutputstream (), Geterrorstream (), For IO streams, if there is a buffer size limit, blocking may occur, resulting in a deadlock condition.

You can use Destory () to force a child process to be killed, Exitvalue () returns the execution result, and if the child process needs to wait for return, call the WAITFOR () method to wait for the current thread until the child process exits.

Second, runtime class

Runtime.getruntime (). EXEC () Gets the process class, and the Exec () method has multiple overloads that can be used to set different parameters for different situations. It is also important to note that the execution of Windows and Linux is different in the wording of the Ming Forest.

 Public Static voidMain (string[] args) {String command= "Notepad.exe Txt.txt"; Try{Process Process=runtime.getruntime (). exec (command); Bufferedinputstream bis=NewBufferedinputstream (Process.getinputstream ()); BufferedReader BR=NewBufferedReader (NewInputStreamReader (bis));                String Line;  while(line = Br.readline ())! =NULL) {System.out.println (line);                } process.waitfor (); if(Process.exitvalue ()! = 0) {System.out.println ("Error!");                } bis.close ();            Br.close (); } Catch(IOException e) {//TODO auto-generated Catch blockE.printstacktrace (); } Catch(interruptedexception e) {//TODO auto-generated Catch blockE.printstacktrace (); }        }

Third, Apache common-exec

It is strongly recommended to use Apache's third-party library, which provides more detailed settings and monitoring methods, and so on.

The command executed is called commandline, and you can use the class's Addargument () method to add parameters to it, and the parse () method wraps the command you provide with an executable command. The command is executed by the Executor executor class, and the Execute () method of the Defaultexecutor class executes the command, and Exitvalue can also return the receive by this method. Setting Executewatchdog can specify how long the process ends after an error, which effectively prevents the run-away process. In addition, Common-exec supports asynchronous execution, executor by setting a Executeresulthandler class where an instance of the class receives the error exception and exit code.

CommandLine CmdLine =NewCommandLine ("AcroRd32.exe"); Cmdline.addargument ("/P"); Cmdline.addargument ("/h"); Cmdline.addargument ("${file}"); HashMap Map=NewHashMap (); Map.put ("File",NewFile ("Invoice.pdf"));    Commandline.setsubstitutionmap (map); Defaultexecuteresulthandler Resulthandler=NewDefaultexecuteresulthandler (); Executewatchdog watchdog=NewExecutewatchdog (60*1000); Executor Executor=NewDefaultexecutor (); Executor.setexitvalue (1);    Executor.setwatchdog (watchdog);    Executor.execute (CmdLine, Resulthandler); //some time later the result handler callback is invoked so we//can safely request the exit value    intExitvalue = Resulthandler.waitfor ();

I. Introduction to Processbuilder and Runtime classes in Java

In Java in order to execute the script or the calling program must pass the Processbuilder and Runtime class, the above two classes choose one of the lines, about them are described as follows:

Both the

Processbuilder.start () and the Runtime.exec () methods are used to create an operating system process (to perform command-line operations) and return an instance of the process subclass that is used to control the status of processes and obtain relevant information. The
Process class provides methods for performing input from a process, performing output to a process, waiting for a process to complete, checking the exit status of a process, and destroying (killing) the process. The method of creating a process may not work well for specific processes on some native platforms, such as native window processes, daemons, win16/dos processes on Microsoft Windows, or shell scripts. The child process created does not have its own terminal or console. All of its standard IO (i.e., stdin, stdout, and STDERR) operations are redirected to the parent process via three streams (Getoutputstream (), getInputStream (), and Geterrorstream ())  . The parent process uses these streams to provide input to the child process and to obtain output from the child process. Because some native platforms only provide a limited buffer size for standard input and output streams, it can cause child processes to block and even deadlock if the output stream or input stream of a child process fails quickly. When there are no more references to the process object, instead of deleting the child process, it continues to execute the child process asynchronously. For Java processes with process objects, it is not necessary to execute the processes represented by the process object asynchronously or concurrently.
Each Processbuilder instance manages a set of process properties. The start () method of the Processbuilder uses these properties to create a new process instance. The start () method can be called repeatedly from the same instance to create a new child process with the same or related properties.
Different points:
The arguments passed by Processbuilder.start () and runtime.exec () differ, and Runtime.exec () accepts a separate string, which is delimited by a space to separate the executable command program and arguments. ; You can also accept string array parameters. The Processbuilder constructor is a list of strings or arrays. The first parameter in the list is the executable command program, and the other is the command-line execution of the required parameters.
by looking at the JDK source code, Runtime.exec is ultimately called Processbuilder to actually perform the operation.

Second, runtime demo example

1. In Windows downgrade DOS command:

The following shows an example of executing the DOS command "ChDir" under windows and executing the output of the result.

 Public classTestdos {/*** Execute DOS command under Windows and output on console side * *@throwsException*/       Public Static voidMain (string[] args)throwsException {String strcmd= "ChDir";//DOS command to be executed (the CHDIR command is to list the current working directory)Process process = Runtime.getruntime (). EXEC ("cmd/k" + strcmd);//execute cmd command with cmd program//process.waitfor (); //Read Screen outputBufferedReader Strcon =NewBufferedReader (NewInputStreamReader (Process.getinputstream ()));          String Line;  while(line = Strcon.readline ())! =NULL) {System.out.println (line); }      }  }  

If you do not need to do screen output, you can simply write the following way:

 public  class         Testdos { /**   * On Windows Downgrade DOS command *   @throws   Ex Ception  */ public  static  void  main (string[] args) throws   Exception {String strcmd  = "DOS command"; //         DOS command to be executed  Runtime.getruntime (). EXEC ("cmd/c" + strcmd). WaitFor (); //  }}  

Note: When executing a DOS command, you need to precede the command with the "cmd/x" parameter, where x can be a C or K value, as specified below:

CMD/C ChDir is the Close command window after the dir command is executed.
cmd/k chdir The Command window is not closed after the dir command is executed.
CMD/C start ChDir will open a new window and execute the dir instruction, the original window will be closed.
cmd/k start ChDir will open a new window and execute the dir instruction, the original window will not be closed.

2. On Windows downgrade with external program:

The following shows the process of calling the QQ program:

 /**   * example of a Windows downgrade using the Microsoft program *  */ public  class       Span style= "COLOR: #000000" > callqq { /**   *   @param   args *   @throws   Exception  */ public  static  void  main (string[] args) throws   Exception {runtime.getruntime (). EXEC ( d:\\program Files (x86) \\Tencent\\QQ\\QQProtect\      \bin\\qqprotect.exe "); }  }  

3. Execute the shell command under Linux:

The following shows the execution of the shell command pwd in Linux and displays the results of the execution:

/*** Execute the Linux shell command and output the results on the console side **/   Public classCallshell {/**      * @throwsException*/       Public Static voidMain (string[] args)throwsException {String strcmd= "PWD";//Execute shell CommandProcess process = Runtime.getruntime (). exec (Strcmd);//calling the Protoc.exe program by executing the cmd commandBufferedReader Strcon =NewBufferedReader (NewInputStreamReader (Process.getinputstream ()));          String Line;  while(line = Strcon.readline ())! =NULL) {System.out.println ("Java Print:" +Line ); }      }  }  

4. Cut the shell script in Linux and output the result:

/*** Cut the shell script on Linux and output the execution result of the script on the console side **/   Public classCallshell {/**      * @throwsException*/       Public Static voidMain (string[] args)throwsException {String strcmd= "/home/zhu/test/test.sh";//shell script to be calledProcess process = Runtime.getruntime (). exec (Strcmd);//calling the Protoc.exe program by executing the cmd commandBufferedReader Strcon =NewBufferedReader (NewInputStreamReader (Process.getinputstream ()));          String Line;  while(line = Strcon.readline ())! =NULL) {System.out.println ("Java Print:" +Line ); }      }  }  

Iii. Examples of Processbuilder use

The following references are used for Processbuilder:

String[] as = new string[]{"Pending command 1", "Pending command 2", ...};
Processbuilder PB = new Processbuilder (AS);
Pb.start ();
Use Processbuilder to execute multiple commands sequentially

Java calls local commands

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.