java执行docker命令

java执行docker命令



前言

整理了关于java用代码执行docker命令的例子。


提示:以下是本篇文章正文内容,下面案例可供参考

一、命令帮助类

package com.venture.saipan.gui.util;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author :feiyang
 * @Date :Created in 4:49 PM 2019/9/26
 */
public class ShellUtils {

    private static ProcessBuilder processBuilder = new ProcessBuilder();

    /**
     * 执行脚本命令
     * @author  feiyang
     * @param commend
     * @return  java.lang.Process
     * @date    2019/9/26
     * @throws
     */
    public static Process exec(List<String> commend) {
        Process process = null;
        try {
            String[] commends = new String[commend.size()];
            commend.toArray(commends);
            processBuilder.command(commends);
            process = processBuilder.start();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return process;
    }

    public static Process exec(String path,List<String> commend) {
        Process process = null;
        try {
            String[] commends = new String[commend.size()];
            commend.toArray(commends);
            processBuilder.command(commends);
            processBuilder.directory(new File(path));
            process = processBuilder.start();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return process;
    }

    public static Process exec(String commendStr) {
        List<String> commend = new ArrayList<>();
        commend.add("cmd");
        commend.add("/c");
        commend.add(commendStr);
        Process process =exec(commend);
        return process;
    }

    /**
     * 在指定路径执行命令
     * @param path
     * @param commendStr
     * @return
     */
    public static Process exec(String path,String commendStr) {
        List<String> commend = new ArrayList<>();
        commend.add("cmd");
        commend.add("/c");
        commend.add(commendStr);
        Process process =exec(path,commend);
        return process;
    }

    /**
     *
     * @author  feiyang
     * @param process
     * @return  java.lang.String
     * @date    2019/9/26
     * @throws
     */
    public static String getOutput(Process process) {
        String output = null;
        BufferedReader reader = null;
        try {
            if (process != null) {
                StringBuffer stringBuffer = new StringBuffer();
                reader = new BufferedReader(new InputStreamReader(process.getInputStream(),"gbk"));
                while (reader.read() != -1){
                    stringBuffer.append("\n" + reader.readLine());
//                    System.out.println(reader.readLine());
                }
                output = stringBuffer.toString();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        closeQuietly(reader);
        return output;
    }

    /**
     * 获取错误信息
     * @author  feiyang
     * @param process
     * @return  java.lang.String
     * @date    2019/9/26
     * @throws
     */
    public static String getError(Process process) {
        String errput = null;
        BufferedReader reader = null;
        try {
            if (process != null) {
                StringBuffer stringBuffer = new StringBuffer();
                reader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
                while (reader.read() != -1){
                    stringBuffer.append("\n" + reader.readLine());
                }
                errput = stringBuffer.toString();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        closeQuietly(reader);
        return errput;
    }

    /**
     * 关流
     * @author  feiyang
     * @param reader
     * @return  void
     * @date    2019/9/26
     * @throws
     */
    public static void closeQuietly(Reader reader) {
        try {
            if (reader != null) {
                reader.close();
            }
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
    }

    /**
     * 终止进程
     * @author  feiyang
     * @param process
     * @return  void
     * @date    2019/9/26
     * @throws
     */
    public static void destroy(Process process) {
        if (process != null) {
            process.destroyForcibly();
        }
    }

    public static Integer waitFor(Process process) {
        Integer exitCode = null;
        if (process != null) {
            try {
                exitCode=process.waitFor();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
        return exitCode;
    }

    /**
     * 执行命令操作
     * @param commend
     */
    public static void dealCommand(String path,List<String> commend,boolean wait){
        Process process;
        if(path !=null){
            process = ShellUtils.exec(path,commend);
        }else{
            process = ShellUtils.exec(commend);
        }
        if(wait){
//            String message = ShellUtils.getOutput(process);
//            String error = ShellUtils.getError(process);
//            System.out.println(message);
//            System.out.println(error);
            Integer exitCode =ShellUtils.waitFor(process);
            if (0 == exitCode) {
                System.out.println("脚本文件执行成功:" + exitCode);
            } else {
                System.out.println("脚本文件执行失败:" + exitCode);
            }
        }
    }

    public static void dealCommandWithPath(String path,String commendStr,boolean wait){
        Process process;
        if(path !=null){
            process = ShellUtils.exec(path,commendStr);
        }else{
            process = ShellUtils.exec(commendStr);
        }
        _dealCommand(process,wait);

    }

    public static void dealCommand(String commendStr,boolean wait){
        Process process= ShellUtils.exec(commendStr);
        _dealCommand(process,wait);
    }

    private static void _dealCommand(Process process,boolean wait){
        if(wait){
//            String message = ShellUtils.getOutput(process);
//            String error = ShellUtils.getError(process);
//            System.out.println(message);
//            System.out.println(error);
            Integer exitCode =ShellUtils.waitFor(process);
            if (0 == exitCode) {
                System.out.println("脚本文件执行成功:" + exitCode);
            } else {
                System.out.println("脚本文件执行失败:" + exitCode);
            }
        }
    }




}

二、使用测试

测试类

代码如下(示例):

import com.venture.saipan.gui.util.ShellUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;


public class CMDExecuteTest {
    public static void main(String[] args) throws IOException {
        //整条命令执行
        String mysqlCommand = "docker cp D:\\docker\\docker-saipan\\corpus_init.sql pgsql:/tmp";
        ShellUtils.dealCommand(mysqlCommand, true);

        //使用powershell执行
        List<String> commend = new ArrayList<>();
        commend.add("powershell.exe");
        commend.add("docker stop $(docker ps -a -q)");
        ShellUtils.dealCommand(null,commend,true);


    }

}


总结

以上就是如何在java中使用ProcessBuilder执行docker命令的方法

  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值