How Java calls shell scripts

Sometimes you will encounter such a scenario: a function point needs to be embedded in the function of java, and this function is realized by shell script. At this time, Java's support for script calls is required.

test environment

Ubuntu16.04 i3-6100,12GB

Hello World

Let's look at a basic example

    Process exec = Runtime.getRuntime().exec(new String[] { "uname" ,"-a"});
    exec.waitFor();
    BufferedReader reader =
            new BufferedReader(new InputStreamReader(exec.getInputStream()));
    System.out.println(reader.readLine());

Linux jason-Inspiron-3650 4.4.0-121-generic #145-Ubuntu SMP Fri Apr 13 13:47:23 UTC 2018 x86_64 x86_64 x86_64 GNU/Linux

Interpretation Process

The java.lang.Process class provides methods to obtain input, output, wait for execution, and destroy processes.
The Process class can create instances through ProcessBuilder.start() and Runtime.exec. Starting from Java 1.5, ProcessBuilder.start() is the more recommended method, but online tutorials more recommend using the Runtime.exec() method.

Modifier and Type Method Description
abstract void destroy () Kills the subprocess.
abstract int exitValue () Returns the exit value for the subprocess.
abstract InputStream getErrorStream () Returns the input stream connected to the error output of the subprocess.
abstract InputStream getInputStream () Returns the input stream connected to the normal output of the subprocess.
abstract OutputStream getOutputStream () Returns the output stream connected to the normal input of the subprocess.
abstract int waitFor () Causes the current thread to wait, if necessary, until the process represented by this Process object has terminated.

In the inheritance system, the implementation class of Process is built in JDK, and the linux version of jdk has only one implementation class like UnixProcess.

interact with scripts

Process can not only execute the process, but also obtain the return result of the process.

    private String executeCommand(String command) {
        StringBuffer output = new StringBuffer();
        Process p;
        try {
            p = Runtime.getRuntime().exec(command);
            int exitCode = p.waitFor();
            System.out.println(exitCode);
            BufferedReader reader =
                    new BufferedReader(new InputStreamReader(p.getInputStream()));
            String line = "";
            while ((line = reader.readLine()) != null) {
                output.append(line + "\n");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(output.toString());
        return output.toString();
    }

PING www.a.shifen.com (111.13.100.91) 56(84) bytes of data.
64 bytes from localhost (111.13.100.91): icmp_seq=1 ttl=52 time=7.66 ms
64 bytes from localhost (111.13.100.91): icmp_seq=2 ttl=52 time=7.90 ms
64 bytes from localhost (111.13.100.91): icmp_seq=3 ttl=52 time=14.0 ms

--- www.a.shifen.com ping statistics ---
3 packets transmitted, 3 received, 0% packet loss, time 2003ms
rtt min/avg/max/mdev = 7.668/9.861/14.013/2.937 ms

Summarize

The way of executing scripts in Java is actually similar to executing scripts directly in bash. The difference is that the environment has changed, and the effect of execution is basically the same as that of bash.

This article was published on the WeChat public account: xiaokele_data.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325977389&siteId=291194637