- Invocation mode
Java calls Linux commands to execute in two ways, one is to call the Linux command directly, one is to write the Linux command into the. Sh script, and then invoke the script to execute.
- Detailed description
Direct invocation: Use the runtime class and the Process class under the Lang packet in Java, where the Runtime.getruntime (). EXEC (Linux command) method can execute Linux commands directly, The process class can receive the return value of the Runtime.getruntime (). EXEC () class, and provides the WaitFor () method and the Destroy () method, WaitFor () The function of the method is to wait for the process to complete before executing the subsequent content, and the Destroy () method acts to destroy the process. The following program shows that all files under the filename path are packaged as a zip archive, using the method called Direct.
Call the shell script: The direct call method has some drawbacks, such as complex command bad implementation, some commands can not be realized and so on. So I recommend implementing a Linux command in a way that invokes a shell script. This is accomplished by first writing the command in the shell script (. sh), and then calling "Sh path/.sh" in Runtime.getruntime (). EXEC (), where path is the route of the shell script. In many cases we need to loop through the same Linux commands to implement our functionality, and we need to pass parameters to the Linux command, as shown in the following example:
The commands in imp.sh are as follows:
1 name=$12 su-oracle-c "imp user/[email protected] Instance name File=filepath full=y ignore=y"
The statement implements the ability to switch to the Oracle directory under the root user, import a. dmp file into the Oracle database using the IMP command, and then return to the root user and put the statement into the for loop to implement multiple. dmp files imported into the Oracle database. Where the file name of the. dmp file is a variable, replaced with name=$1 in the shell command, in the Linux command, ${name} refers to the file name, the value of the parameter is passed in the call, and the Linux command $1,$2 ... $n are placeholder variables that are used sequentially when using variables. Assigned values are assigned in the appropriate order.
Java calls Linux command execution