Java执行shell命令

添加依赖 #

首先使用Spring Boot开启一个RESTful项目,额外的加上Apache Commons Exec的依赖。

Exec官网1API文档

1
2
3
4
5
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-exec</artifactId>
    <version>1.3</version>
</dependency>

代码实现 #

这里分两种情况。一个是最简的只关心执行是否成功,也就是code大于0为失败;另一个是需要拿到执行的标准输出和错误的信息。

只关心是否成功 #

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
@Service
public class MainService {
    public Integer updateBlogFromGit(){
        // 1
        CommandLine pull = CommandLine.parse("git pull");

        // 2
        DefaultExecutor executor = new DefaultExecutor();
        executor.setWorkingDirectory(new File("/home/ubuntu/blog"));

        // 3,省略try_catch
        int exitValue = executor.execute(pull);
        if (exitValue == 0) {
            exitValue = executor.execute(hugo);
        }
        return exitValue;
    }
}
  1. 准备要运行的shell命令
  2. 创建执行器,并设置工作目录
  3. 最后执行命令,返回code

要拿到标准输出和错误的信息 #

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
@Service
public class MainService {
    public String updateBlogFromGit(){
        // 1
        CommandLine pull = CommandLine.parse("git pull");
        CommandLine hugo = CommandLine.parse("hugo");

        // 2
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ByteArrayOutputStream errorStream = new ByteArrayOutputStream();
        PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream, errorStream);

        // 3
        DefaultExecutor executor = new DefaultExecutor();
        executor.setWorkingDirectory(new File("/home/ubuntu/blog"));
        executor.setStreamHandler(streamHandler);

        // 4
        try {
            int exitValue = executor.execute(pull);
            if (exitValue == 0) {
                exitValue = executor.execute(hugo);
            }
            String result;
            if(exitValue==0){
                result= outputStream.toString();
            } else {
                result = errorStream.toString();
            }
            return result;
        } catch (ExecuteException e) {
            return errorStream.toString();
        } catch (IOException e) {
            return e.getMessage();
        }
    }
}
  1. 准备要运行的shell命令
  2. 准备接收标准输出和错误的Stream
  3. 创建执行器,并设置工作目录,设置StreamHandler
  4. 最后执行命令(如果执行时出错会返回大于0的整数),返回标准输出或错误信息或报错堆栈信息

收获 #

技能树:

后端 --> Java --> 工具库 --> Exec --> 使用
后端 --> Java --> 语言基础 --> ByteArrayOutputStream --> 使用

其他相关内容 #