Implement Linux commands in Java

Source: Internet
Author: User

The Linux commands to be executed in Java programs mainly depend on two classes: process and runtime.

First, let's take a look at the process class:

[Plain]
View plaincopyprint?
  1. Processbuilder. Start () and runtime.exe C create a local process and return an instance of the Process subclass,
  2. This instance can be used to control processes and obtain relevant information. The process class provides execution from process input, execution output to process, waiting for the process to complete,
  3. Check the exit status of the process and the method for destroying (killing) the process.
  4. The Process Creation method may not work well for specific processes on some local platforms, such as the Local Window Process, daemon process, Microsoft Windows
  5. On the Win16/DOS process, or shell script. The created sub-process does not have its own terminal or console. All its standard io (namely stdin, stdout, and stderr)
  6. All operations are redirected to the parent process through three streams (getoutputstream (), getinputstream (), and geterrorstream.
  7. The parent process uses these streams to provide the input to the child process and obtain the output from the child process. Some local platforms only provide limited Buffer Sizes for standard input and output streams,
  8. If the output stream or input stream of the read/write sub-process rapidly fails, the sub-process may be blocked or even cause a deadlock.
  9. When there is no more reference to the process object, instead of deleting the sub-process, the sub-process will continue to be executed asynchronously.
  10. For Java processes with process objects, there is no need to execute processes represented by process objects asynchronously or concurrently.
Processbuilder. Start () and runtime.exe C create a local process and return an instance of the Process subclass. This instance can be used to control the process and obtain relevant information. The process class provides methods to execute processes from process input, execution output to process, wait for the process to complete, check the exit status of the process, and destroy (kill) the process. The Process Creation method may not work well for certain processes on the local platform, such as Windows processes, Daemon Processes, Win16/DOS processes on Microsoft Windows, or shell scripts. The created sub-process does not have its own terminal or console. All of its standard io (namely stdin, stdout, and stderr) operations will be redirected to the parent process through three streams (getoutputstream (), getinputstream (), and geterrorstream. The parent process uses these streams to provide the input to the child process and obtain the output from the child process. Some local platforms only provide limited Buffer Sizes for standard input and output streams. If the output stream or input stream of the read/write sub-process fails rapidly, the sub-process may be blocked, A deadlock even occurs. When there is no more reference to the process object, instead of deleting the sub-process, the sub-process will continue to be executed asynchronously. For Java processes with process objects, there is no need to execute processes represented by process objects asynchronously or concurrently.

Note:

1. The created sub-process does not have its own terminal console, and all annotation operations will pass through three streams

(Getoutputstream (), getinputstream (), and geterrorstream () are redirected to the parent process (parent processes can use these streams to determine the execution status of child processes)

2. Some local platforms only provide a limited buffer size for the standard input and output streams. If the output or input stream of the read and write sub-processes rapidly fails,

The sub-process may be blocked or even cause deadlocks.

[Plain]
View plaincopyprint?
  1. Abstract void destroy ()
  2. Kill the child process.
  3. Abstract int exitvalue ()
  4. Returns the export value of the sub-process. According to the Convention, the value 0 indicates normal termination.
  5. Abstract inputstream geterrorstream ()
  6. Gets the error stream of the sub-process.
  7. Abstract inputstream getinputstream ()
  8. Obtains the input stream of a sub-process.
  9. Abstract outputstream getoutputstream ()
  10. Obtain the output stream of the sub-process.
  11. Abstract int waitfor ()
  12. This causes the current thread to wait. If necessary, wait until the process indicated by this process object has been terminated.
  13. If the child process has been terminated, this method returns immediately. If the sub-process is not terminated, the called thread is blocked until the sub-process exits.
Abstract void destroy (): kills sub-processes. Abstract int exitvalue () returns the export value of the child process. According to the Convention, the value 0 indicates normal termination. Abstract inputstream geterrorstream () gets the error stream of the sub-process. Abstract inputstream getinputstream () obtains the input stream of a sub-process. Abstract outputstream getoutputstream () obtains the output stream of a sub-process. Abstract int waitfor () causes the current thread to wait. If necessary, wait until the process indicated by the process object is terminated. If the child process has been terminated, this method returns immediately. If the sub-process is not terminated, the called thread is blocked until the sub-process exits.

Note: If the input stream in the sub-process contains a large number of content in the output stream or error stream, it is best to use the cache (note the above situation 2)

Let's take a look at the runtime class:

[Plain]
View plaincopyprint?
  1. Each Java application has a runtime class instance, enabling the application to be connected to the running environment. You can use the getruntime method to obtain the current runtime environment.
  2. Applications cannot create their own runtime instances.
Each Java application has a runtime class instance, enabling the application to be connected to the running environment. You can use the getruntime method to obtain the current runtime environment. Applications cannot create their own runtime instances.

The following describes the methods:

[Plain]
View plaincopyprint?
  1. Process exec (string command)
  2. Execute the specified string command in a separate process.
  3. Process exec (string command, string [] envp)
  4. Execute the specified string command in a separate process of the specified environment.
  5. Process exec (string command, string [] envp, file DIR)
  6. Execute the specified string command in an independent process in the specified environment and working directory.
  7. Process exec (string [] cmdarray)
  8. Execute the specified command and variable in a separate process.
  9. Process exec (string [] cmdarray, string [] envp)
  10. Execute the specified command and variable in the independent process of the specified environment.
  11. Process exec (string [] cmdarray, string [] envp, file DIR)
  12. Execute specified commands and variables in independent processes in the specified environment and working directory.
Process exec (string command) executes the specified string command in a separate process. Process exec (string command, string [] envp) executes the specified string command in a separate process in the specified environment. Process exec (string command, string [] envp, file DIR) executes the specified string command in an independent process in the specified environment and working directory. Process exec (string [] cmdarray) executes the specified command and variable in a separate process. Process exec (string [] cmdarray, string [] envp) executes the specified command and variable in the independent process of the specified environment. Process exec (string [] cmdarray, string [] envp, file DIR) executes the specified commands and variables in the independent processes in the specified environment and working directory.
command:A specified system command.
envp: Environment Variable string array. The setting format of each environment variable is name = value. If the child process should inherit the environment of the current process, this parameter is null.
dir: The working directory of the child process. If the child process should inherit the working directory of the current process, this parameter is null.
Cmdarray: array containing the called command and its parameters.

The following is an example (to compress an executable jar package to Linux ):

[Java]
View plaincopyprint?
  1. Public class test {
  2. Public static void main (string [] ARGs ){
  3. Inputstream in = NULL;
  4. Try {
  5. Process pro = runtime.getruntime(cmd.exe C (New String [] {"sh ",
  6. "/Home/test. Sh", "Select Admin from m_admin ",
  7. "/Home/test/result.txt "});
  8. Pro. waitfor ();
  9. In = pro. getinputstream ();
  10. Bufferedreader READ = new bufferedreader (New inputstreamreader (in ));
  11. String result = read. Readline ();
  12. System. Out. println ("info:" + result );
  13. } Catch (exception e ){
  14. E. printstacktrace ();
  15. }
  16. }
  17. }
public class test {public static void main(String[] args){InputStream in = null;try {Process pro = Runtime.getRuntime().exec(new String[]{"sh",                                 "/home/test/test.sh","select admin from M_ADMIN",                                 "/home/test/result.txt"});pro.waitFor();in = pro.getInputStream();BufferedReader read = new BufferedReader(new InputStreamReader(in));String result = read.readLine();System.out.println("INFO:"+result);} catch (Exception e) {e.printStackTrace();}}}

Here we use the process exec (string [] cmdarray) method.

The/home/test. Sh script is as follows:

[Plain]
View plaincopyprint?
  1. #! /Bin/sh
  2. # Querying SQL
  3. SQL = $1
  4. # Save the query result File
  5. Result_file = $2
  6. # Database Connection
  7. Db_name = Scott
  8. Db_pwd = Tiger
  9. Db_server = db_test
  10. Result = 'sqlplus-S $ {db_name}/$ {db_pwd }@$ {db_server} <!
  11. Set heading off
  12. Set echo off
  13. Set pages 0
  14. Set feed off
  15. Set linesize 3000
  16. $ {SQL}
  17. /
  18. Commit
  19. /
  20. ! '
  21. Echo "$ {result}" >$ {result_file}
  22. Echo 0;

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.