命令行工具类

业务需要,要求程序实现指定磁盘挂载功能。该功大致实现思路为使用java调用命令行工具,再利用命令行发送命令请求。其中命令又分为交互式命令和非交互式命令两类,后续有空打算直接将这俩类方法合并为更通用的方法。以下为命令行工具类具体代码实现:

package com.lyb.demo;

import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import java.io.*;

/**
 * 命令行工具类
 *
 * @author lyb
 * @date 2023/12/19
 */
@Slf4j
public class CommandUtils {
	
	private static final String MSG_EXEC_LINE = "-----------------command exec msg : {}";
    private static final String MSG_RET_CODE = "-----------------command ret code : {}";
    
    public static void exec(String[] commands) {
        try {
            ProcessBuilder pb = new ProcessBuilder();
            pb.command(commands);
            pb.redirectErrorStream(true);
            Process p = pb.start();
            String line;
            BufferedReader stdout = new BufferedReader(new InputStreamReader(p.getInputStream()));
            while ((line = stdout.readLine()) != null) {
                log.info(MSG_EXEC_LINE, line);
            }
            int retCode = p.waitFor();
            log.info(MSG_RET_CODE, retCode);
            stdout.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    public static void execWithInteraction(String dirPath, String[] commands, String params) {
        try {
            ProcessBuilder pb = new ProcessBuilder(commands);
            if (StrUtil.isNotBlank(dirPath)) {
                pb.directory(new File(dirPath));
            }
            pb.redirectErrorStream(true);
            Process p = pb.start();
            Writer writer = new OutputStreamWriter(p.getOutputStream());
            writer.write(params);
            writer.flush();
            writer.close();
            int retCode = p.waitFor();
            log.info(MSG_RET_CODE, retCode);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
  • 6
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值