How to properly apply Runtime class calls

xiaoxiao2021-03-06  24

When writing applications with Java, sometimes you need to call another ready-made executable or system command in the program, which can be implemented by combining the Runtime class with Java and Process classes. Below is a relatively typical program mode: ... process process = runtime.getRuntime (); exec (". P.exe"); process.waitfor (); ... in the above program, the first line ".p "Is the program name to be executed, Runtime.Getruntime () returns the Runtime object of the current application that indicates that the Java virtual machine creates a child process to perform the specified executable and return to the child. Process object instance corresponding to the process. The information of the sub-process or the information of the child process can be controlled by Process. The purpose of the second statement is waiting for the sub-process to complete down. But on the Windows platform, if it is handled properly, it is sometimes not available. Below is a few need to pay attention to the author in actual programming: 1. Internal command executing DOS If you want to execute a DOS internal command, there are two ways. One method is to include the command interpreter in the parameter of the exec (). For example, execute the DIR command, on NT, can be written into Exec ("cmd.exe / c dir"), under Windows 95/98, can be written as "command.exe / c dir", where parameter "/ c" indicates command Turn off the window immediately after execution. Another method is to put the internal command in a batch command my_dir.bat file, written into Exec ("my_dir.bat") in the Java program. If you only write to Exec ("Dir"), the Java virtual machine will report an error when running. The former method To ensure the portability of the program, you need to read the running operating system platform in the program to call different command interpreters. The latter method does not need to do more processing. 2. Open an unhappun file to open an unhaffably file, but there is two ways to associate an associated application. Taken a Word document A.DOC file as an example, Java can have the following two ways: Exec ("start .a.doc"); Exec ("C: Program FileSmicrosoft OfficeOfficeWInword.exe .a.doc"); The former method is more simple and convenient. 3. Perform a DOS executor with a standard output on the Windows platform, running the DOS window of the called program is often closed after the program is executed, causing the Java application to block in WaitFor (). One possible reason for this phenomenon is that the standard output buffer of the executable program is not large enough. The solution is that the method provided by Java provides the Java virtual machine intercepting the standard output of the DOS run window of the called program, and reads the contents of the window's standard output buffer before the waitfor () command.

转载请注明原文地址:https://www.9cbs.com/read-42664.html

New Post(0)