Java Magic Hall: Find the weapon of foreign aid--runtime.exec detailed

Source: Internet
Author: User
Tags string format

First, preface

Java although perfectly formed but always have a weakness, such as the acquisition of hardware information such as CPU, of course, we can be obtained by JNI calls to C + +, but for the C/s and Windows API is not familiar with the code of the farmers is a series of complex learning and the pit process. Can it be done in a way that is simpler and less expensive to learn? The answer is yes, in the case of functional implementation in the first place, to borrow his mountain stone is the most concise and powerful approach. And the Runtime.exec method opens up such a path for us.

Second, the understanding Java.lang.Runtime.exec method

function: used to invoke external programs and redirect external programs ' standard input, standard output, and standard errors to the buffer pool. The function is the same as the "Run" of Windows.

Method Overloads:

exec (String command) , calls an external program, and the entry command is the startup path or command for an externally executable program.

exec (string[] cmdarray) , calling an external program, the element that is in the parameter Cmdarray will be combined into a full external executable's startup path or command.

exec (String command, string[] envp) , set the system environment variable before calling the external program, which is used only for command entry, envp each element as a system environment variable, and the string format is "environment variable name = environment variable value.

exec (String command, string[] envp, File dir) , in addition to setting the system environment variable, also sets the current working directory through the entry dir.

Instance--Executes the dir command in the current directory and saves the result to a c:\dir.txt text file:

Premise: Assume that the current user's home directory is C:\user\fsjohnhuang

Directory structure under C:\user\fsjohnhuang

|--|--test.txt

Directory structure under D:\test

d:\test|--movies|--readme.txt

Code Snippets

Runtime r =runtime.getruntime ();Try{Process proc= R.exec ("cmd/c dir >%dest%",Newstring[]{"Dest=c:\\dir.txt",NewFile ("d:\\test")}); intExitval = Proc.waitfor ();//blocks the current thread and waits for the external program to abort after obtaining the result codeSystem. out. println (Exitval = =0?"Success":"failed");}Catch(Exception e) {e.printstacktrace ();}

After executing the code, view the contents of the C:\dir.txt file as follows:

8074-B214 D:\test's catalogue    :    <DIR>          Movies/at/from  :             8,642 Readme.txt

Third, the attention point

1. runtime.exec () is not a cmd or shell environment, so commands such as Dir cannot be called directly. To invoke commands under the command line, refer to the example in section 2nd.

2. Through the process instance. getInputStream () and process instances. Geterrorstream () gets the input stream and the error stream that is provided by the buffer pool to the current Java program, Instead of getting the standard output stream and standard error stream of the external program directly.

The capacity of the buffer pool is certain, so if the external program continues to output content to the buffer pool while it is running, when the buffer pool fills up, the external program pauses until the buffer pool has empty space to receive the output from the external program. (This problem occurs when you copy a large number of files with the xcopy command)

The solution is that the current Java program reads the contents of the buffer pool continuously, thus freeing up the buffer pool space.

Four, definitely the pit

To address the issues mentioned in the 2nd note of section 3rd. We can deal with the following two ways

Runtime r =runtime.getruntime ();Try{Process proc= R.exec ("cmd/c dir");//assume that the operation is causing a large amount of content output//use a character stream to read buffer pool content and make roomBufferedReader reader =NewBufferedReader (NewInputStreamReader (Proc.getinputstream (),"GBK"))); String Line=NULL;  while(line = Reader.readline ())! =NULL) {System. out. println (line); }  //or use a byte stream to read the buffer pool contents, make room//Bytearrayoutputstream pool = new Bytearrayoutputstream (); //byte[] buffer = new byte[1024]; //int count =-1; //While ((count = Proc.getinputstream (). Read (buffer))! =-1) {//pool.write (buffer, 0, count); //buffer = new byte[1024]; // }  //System.out.println (pool.tostring ("GBK"));  intExitval =proc.waitfor (); System. out. println (Exitval = =0?"Success":"failed");}Catch(Exception e) {e.printstacktrace ();}

Here is a pit: the external program will automatically shut down after execution, otherwise, whether it is a character stream or a byte stream, there is a case where the Java process is blocked because it cannot read the data and cannot read the stream terminator.

and cmd/c is telling the CMD environment process to close itself when execution is complete.

V. Summary

With the right tools to do the right thing, the Runtime.exec method allows us to implement the means of function more flexibly!

Respect the original, reprint please indicate from: http://www.cnblogs.com/fsjohnhuang/p/4081445.html ^_^ Fat Boy John

Vi. references

http://fuliang.iteye.com/blog/574260

Java Magic Hall: Find the weapon of foreign aid--runtime.exec detailed

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.