Use Java to call system programs

I. Overview

Runtime class

The Runtime class encapsulates the runtime environment.

Every Java application has an instance of the Runtime class, enabling the application to connect to the environment in which it runs.

Generally, you cannot instantiate a Runtime object, and the application cannot create your own Runtime class instance, but you can get a reference to the current Runtime runtime object through the getRuntime method.

Once you get a reference to the current Runtime object, you can call the method of the Runtime object to control the state and behavior of the Java virtual machine.

Process class

The Process class is an abstract class (all methods are abstract), encapsulating a process (ie an executive program).

The Process class provides methods to execute from process input, execution output to the process, wait for the process to complete, check the exit status of the process, and destroy (kill) the process. The ProcessBuilder.start () and Runtime.exec methods create a native process and return an instance of the Process subclass, which can be used to control the process and obtain relevant information.

The process creation method may not work well for specific processes on some native platforms, such as native window processes, daemon processes, Win16 / DOS processes on Microsoft Windows, or shell scripts. The created child process does not have its own terminal or console. All its standard io (ie stdin, stdout, stderr) operations will be redirected to the parent process through three streams (getOutputStream (), getInputStream (), getErrorStream ()). The parent process uses these streams to provide input to and obtain output from the child process. Because some local platforms only provide a limited buffer size for standard input and output streams, if the output stream or input stream of the read and write subprocess fails quickly, it may cause the subprocess to block or even deadlock.

ProcessBuilder class

The ProcessBuilder class is a new class added in java.lang by J2SE 1.5. This class is used to create operating system processes. It provides a method for starting and managing processes (that is, applications). Before J2SE 1.5, the Process class was used to control and manage the process.

Each ProcessBuilder instance manages a set of process attributes. Its start () method uses these attributes to create a new Process instance. The start () method can be called repeatedly from the same instance to create a new child process with the same or related attributes.

ProcessBuilder provides more control for the process, for example, you can set the current working directory, you can also change the environmental parameters. The function of Process is relatively simple.
       ProcessBuilder is a final class, there are two constructors with parameters, you can directly create ProcessBuilder objects through the constructor. Process is an abstract class, and its instances are generally created indirectly through Runtime.exec () and ProcessBuilder.start ().

note: 

Modifying the properties of the process builder will affect subsequent processes started by the object's start () method, but will never affect previously started processes or Java's own processes.
      The ProcessBuilder class is not synchronized. If multiple threads access a ProcessBuilder at the same time, and at least one of the threads modifies one of its attributes structurally, it must maintain external synchronization.

Second, common applications  

1. Get RunTime Information

/**
 * 获取runTime信息
 */
public static void GetRuntimeInfo(Runtime runtime) {
    // 返回 Java 虚拟机试图使用的最大内存量,默认是系统的1/4
    System.out.println("最大内存:" + runtime.maxMemory());
    // 返回 Java 虚拟机中的内存总量,默认是系统的1/64
    System.out.println("内存总量:" + runtime.totalMemory());
    // 返回 Java 虚拟机中的空闲内存量
    System.out.println("空闲内存:" + runtime.freeMemory());
    // 向 Java 虚拟机返回可用处理器的数目
    System.out.println("可用CPU数:" + runtime.availableProcessors());
}

Example: GetRuntimeInfo (runtime); runtime.gc (); GetRuntimeInfo (runtime); observe the change of printing information.

2. Execute the command (in a separate process)

/**
 * 执行命令调用程序
 */
public static void executeCmd(String strCmd) {
    Runtime runtime = Runtime.getRuntime();
    try {
        runtime.exec(strCmd);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

Example: executeCmd ("notepad.exe"); Open the system notepad.

3. Get the return value at the end of the child process

Runtime r = Runtime.getRuntime();
Process p = null;
try{
    p = r.exec("notepad");
    p.waitFor(); // 等待子进程结束
} catch (Exception e) {
    System.out.println("Error executing notepad.");
}
System.out.println("Notepad returned " + p.exitValue()); // 子进程返回值

4.

ProcessBuilder processBuilder = new ProcessBuilder();
processBuilder.command("ping","127.0.0.1");
//将标准输入流和错误输入流合并,通过标准输入流读取信息
processBuilder.redirectErrorStream(true);
try {
    //启动进程
    Process process = processBuilder.start();
    //获取输入流
    InputStream inputStream = process.getInputStream();
    //转成字符输入流
    InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "gbk");
    int len = -1;
    char[] c = new char[1024];
    StringBuffer outputString = new StringBuffer();
    //读取进程输入流中的内容
    while ((len = inputStreamReader.read(c)) != -1) {
        String s = new String(c, 0, len);
        outputString.append(s);
        System.out.print(s);
    }
    inputStream.close();
} catch (IOException e) {
    e.printStackTrace();
}

5. More usage methods view the official API

 

reference:

 

Published 19 original articles · Like9 · Visits 2999

Guess you like

Origin blog.csdn.net/Necrolic/article/details/105431040