已复制
全屏展示
复制代码

Java调用并执行外部Linux命令


· 2 min read

一. pom依赖

Java 调用 linux 命令,执行 linux 命令。

<dependency>
  <groupId>org.apache.commons</groupId>
  <artifactId>commons-exec</artifactId>
  <version>1.3</version>
</dependency>

二. 同步调用

package org.example;

import org.apache.commons.exec.CommandLine;
import org.apache.commons.exec.DefaultExecutor;
import org.apache.commons.exec.PumpStreamHandler;

import java.io.ByteArrayOutputStream;

class Main {
    public static void main(String[] args) throws Exception {
        String command = "ping -c 3 127.0.0.1";
        // 接收正常结果流
        ByteArrayOutputStream susStream = new ByteArrayOutputStream();
        // 接收异常结果流
        ByteArrayOutputStream errStream = new ByteArrayOutputStream();
        
        CommandLine commandLine = CommandLine.parse(command);
        DefaultExecutor executor = new DefaultExecutor();
        PumpStreamHandler streamHandler = new PumpStreamHandler(susStream, errStream);
        executor.setStreamHandler(streamHandler);
        int code = executor.execute(commandLine);
        System.out.println("result code: " + code);
        
        String suc = susStream.toString();
        String err = errStream.toString();
        System.out.println("success:");
        System.out.println(suc);
        System.out.println("error:");
        System.out.println(err);
    }
}

三. 异步调用

package org.example;

import org.apache.commons.exec.CommandLine;
import org.apache.commons.exec.DefaultExecuteResultHandler;
import org.apache.commons.exec.DefaultExecutor;
import org.apache.commons.exec.ExecuteException;
import org.apache.commons.exec.PumpStreamHandler;

import java.io.ByteArrayOutputStream;

class Main {
    public static void main(String[] args) throws Exception {
        String command = "ping -c 3 127.0.0.1";

        // 接收正常结果流
        ByteArrayOutputStream susStream = new ByteArrayOutputStream();
        // 接收异常结果流
        ByteArrayOutputStream errStream = new ByteArrayOutputStream();

        CommandLine commandLine = CommandLine.parse(command);
        DefaultExecutor executor = new DefaultExecutor();
        PumpStreamHandler streamHandler = new PumpStreamHandler(susStream, errStream);
        executor.setStreamHandler(streamHandler);
        DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler() {
            @Override
            public void onProcessComplete(int exitValue) {
                String suc = susStream.toString();
                System.out.println("success:"+exitValue);
                System.out.println(suc);
                System.out.println("3.异步执行完成");

                // 这个必须加, 否者程序不退出
                super.onProcessComplete(exitValue);
            }

            @Override
            public void onProcessFailed(ExecuteException e) {
                String err = errStream.toString();
                System.out.println("error:");
                System.out.println(err);
                System.out.println("3.异步执行出错");

                // 这个必须加, 否者程序不退出
                super.onProcessFailed(e);
            }
        };
        System.out.println("1. 开始执行");
        executor.execute(commandLine, resultHandler);
        System.out.println("2. 做其他操作");

        // 避免主线程退出导致程序退出
        while (!resultHandler.hasResult()) {
            Thread.sleep(100);
        }

    }
}

四. 特殊情况

当执行的命令有参数时,构建 commandLine 要特殊处理,比如命令 impala-shell -q "REFRESH db.table",这种命令必须使用下面的方式创建。

CommandLine commandLine = CommandLine.parse("impala-shell");
commandLine.addArgument("-q", false);
commandLine.addArgument("REFRESH db.table", false);
🔗

文章推荐