Introduction and use of the Java process ProcessBuilder class, ProcessBuilder calls external programs to execute shell commands Linux commands

Table of contents

Introduction and use of ProcessBuilder class

【Preface】

【text】

--Construction method--

--Common method--

--skills--

--Call local Shell command, example--

【Summarize】

【Notice】


Introduction and use of ProcessBuilder class

【Preface】

        When working on a project, it is necessary to dynamically execute JAVA commands at runtime. The initial idea is to generate a bat script at runtime, and then execute the bat script through the exec method of the Runtime class, but the disadvantage of this method is that when the script is executed A cmd program interface box will pop up. Later, when referring to the source code of YANG, I found another method to execute JAVA commands at runtime. From this extension, I learned the function and usage of the PorcessBuilder class.

        The ProcessBuilder class is a new class added by J2SE 1.5 in java.lang. This class is used to create operating system processes, and it provides a method to start and manage processes (that is, applications). Before J2SE 1.5, the process control and management were implemented by the Process class. Each ProcessBuilder instance manages a set of process attributes. Its start() method uses these properties to create a new Process instance. The start() method can be called repeatedly from the same instance to create new child processes with the same or related attributes.

【text】

The ProcessBuilder class is a basic class under the java.lang package, which can be used directly without importing. It is mainly used to create and run various external programs, such as javac, java and so on.

--Construction method--

it(List<String> command), it(String... command)

--Common method--

void command(String... command) is used to pass the command to be executed and parameters to it;

Process start() executes the command and returns a Process object, which is used to obtain the input and output of the execution program;

void directory(File base) is used to set the working directory of the command to be executed, which can not be set;

// ProcessBuilder API

//构造方法 
//利用指定的操作系统程序和参数构造一个进程生成器。 
ProcessBuilder(List<String> command) 
//利用指定的操作系统程序和参数构造一个进程生成器。
ProcessBuilder(String… command) 

//方法 
//返回此进程生成器的操作系统程序和参数。 
command() 
//设置此进程生成器的操作系统程序和参数。 
command(List<String> command) 
//设置此进程生成器的操作系统程序和参数。 
command(String… command) 

//返回此进程生成器的工作目录。 
directory() 
//设置此进程生成器的工作目录。
directory(File directory) 
//返回此进程生成器环境的字符串映射视图。 environment方法获得运行进程的环境变量,得到一个Map,可以修改环境变量 
environment() 
//返回进程生成器是否合并标准错误和标准输出;true为合并,false为不合并
redirectErrorStream() 
//设置此进程生成器的 redirectErrorStream 属性。默认值为false不合并
redirectErrorStream(boolean redirectErrorStream) 
//使用此进程生成器的属性启动一个新进程。
start() 

--skills--

1. When using it, it is recommended to encapsulate it, which is more convenient to use, for example,

public class ProcessUtil {

    public static void process(String... command) throws Exception {
        process((File)null, command);
    }

    public static void process(List<String> commandList) throws Exception {
        process((File)null, (String[])commandList.toArray(new String[0]));
    }

    public static void process(File base, String... command) throws Exception {
        ProcessBuilder processBuilder = new ProcessBuilder(new String[0]);
        if (base != null) {
            processBuilder.directory(base);
        }
        processBuilder.command(command);
        Process process = processBuilder.start();
......

Add an input2string() method to convert the output obtained by executing the program into a String object for easy output, for example,

public static String input2str(InputStream inputStream) throws UnsupportedEncodingException {
        ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];

        try {
            int len;
            while((len = inputStream.read(buffer)) != -1) {
                outSteam.write(buffer, 0, len);
            }
            outSteam.close();
            inputStream.close();
        } catch (IOException var5) {
            var5.printStackTrace();
        }
        return outSteam.toString("utf-8");
    }

Call the local FFMPEG command, example:

  

【Summarize】

As a JAVA underlying class, it enables developers to interact powerfully with the operating system, and when using it to call system commands, it can be done in the background, without the trouble of popping up the cmd command execution box when using the Runtime class. Very convenient. In the following study, you can learn more about the usage of the System class.

【Notice】

After using Runtime.getRuntime().exec() or ProcessBuilder(array).start() to create a subprocess Process, be sure to remove the output information and error information of the subprocess in time, otherwise the output information flow and error information flow are likely to Because too much information leads to being filled, eventually the child process is blocked and cannot be executed.

Typical usage should be:

Reference: Java process Runtime, Process, ProcessBuilder calls external programs - Programmer Architecture Blog - CSDN Blog


If this article is helpful to you, I am very happy to help you.

Of course, if you think there is something in the article that makes you feel unreasonable, or there is an easier way to implement it, or there is something you don’t understand, I hope you can point it out in the comments after reading it, and I will read it as soon as possible reply you.

Guess you like

Origin blog.csdn.net/chenthe1/article/details/131241341