Sometimes our Java calls a program outside of the system
You may need to call a program outside the system, and you can use Runtime.getruntime (). EXEC () to call, and he will generate a new process to run the calling program.
This method returns an Java.lang.Process object that can result in the running of a process that was previously opened, and can manipulate the input and output streams of the process.
The process object has several methods:
1, Destroy () kill this child process
2. Exitvalue () Gets the return status after the process has finished running
3. WaitFor () Gets the return status after the process has finished running, and waits until the process finishes running to know that execution is complete
4, getInputStream () get the standard output flow of the process
5, Geterrorstream () get the error output stream of the process
6. Getoutputstream () gets the input stream of the process
Now speaking of Exitvalue (), when the thread does not complete the call this method will run out Illegalthreadstateexception exception, the most straightforward solution is to use the WAITFOR () method instead.
However, the WAITFOR () method also has obvious drawbacks because the Java program allocates a small buffer to the output stream of the process, sometimes causing the buffer to fill up when the process output information is large, and blocking if the program is not handled in a timely manner. If the program does not process the output stream of the process, it will cause the thread that executes exec () to block forever, and the process will not execute until the output stream is processed or the Java program ends.
The solution is to handle the information in the buffer and open two threads to handle the standard output stream and the error output stream, respectively.
The procedure is as follows:
public class Exectest {public static void Main (string[] args) throws IOException, interruptedexception { String cmd = "cmd/c dir c:\\windows"; Final Process process = Runtime.getruntime (). exec (cmd); Printmessage (Process.getinputstream ()); Printmessage (Process.geterrorstream ()); int value = Process.waitfor (); System.out.println (value); } private static void Printmessage (final inputstream input) { new Thread (new Runnable () {public void run () {
Reader reader = new InputStreamReader (input); BufferedReader bf = new BufferedReader (reader); String line = null; try { while ((Line=bf.readline ())!=null) { System.out.println (line); } } catch (IOException e) { e.printstacktrace (); } } ). Start ();} }
As in the program, read the output information of the process and print to the console will not be blocked, the program can end normally.
Tips
CMD command does not need to add cmd/c to execute, otherwise Java will go to path to find Dir.exe
In Windows general character set encoding for GBK, you need to specify GBK encoding when converting to reader.
Java calls a program outside the system