MangoCool

在linux上使用java exec执行多条cmd

2022-07-22 17:29:51   作者:MangoCool   来源:网络

CmdUtils工具类

import com.aolian.platform.common.exception.ServiceException;
import com.aolian.platform.common.validate.Error;
import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

@Slf4j
public class CmdUtils {

    public static String execCmd(String command) {
        if(EvnUtils.isLocal()) {
            return null;
        }
        log.info("command:{}", command);
        String[] cmd = new String[]{"/bin/bash", "-c", command};
        Process process = null;
        try {
            process = Runtime.getRuntime().exec(cmd);
            // 输出结果,必须写在 waitFor 之前
            String outStr = getStreamStr(process.getInputStream());
            log.info("outStr:{}", outStr);
            // 错误结果,必须写在 waitFor 之前
            String errStr = getStreamStr(process.getErrorStream());
            log.info("errStr:{}", errStr);
            int exitValue = process.waitFor();
            log.info("exitValue:{}", exitValue);
            if (0 != exitValue) {
                throw new ServiceException(new Error(13998, errStr));
            }
            return outStr;
        } catch (Exception e) {
            log.error("----error-----");
            e.printStackTrace();
            throw new ServiceException(new Error(13999, e.getMessage()));
        } finally {
            if (process != null) {
                process.destroy();
            }
        }
    }

    static String getStreamStr(InputStream is) {
        StringBuilder sb = new StringBuilder();
        try (BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF8"))) {
            String line;
            while ((line = br.readLine()) != null) {
                sb.append(line).append("\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return sb.toString();
    }
}


测试代码:

public static void main(String[] args) {
	String cmdSeparator = " && ";
	StringBuilder cmdSb = new StringBuilder();
	cmdSb.append("cd /home").append(cmdSeparator);
	cmdSb.append("ls");
	CmdUtils.execCmd(cmdSb.toString());
}


更多分隔符使用描述:

& [...]  command1 & command2

用于在一个命令行中分隔多个命令。先运行第一个命令,然后运行第二个命令。

&& [...]  command1 && command2
只有当符号前面的命令成功时,才能运行&&后面的命令。
|| [...]  command1 || command2
当||前面的命令执行失败时,才会执行||后面的命令。运行第一个命令,然后仅在第一个命令没有成功完成时才运行第二个命令(接收到大于零的错误码)。
( ) [...]  (command1 & command2)
用于组合或嵌套多个命令。
; or , command1 parameter1;parameter2
用于分隔命令参数。


参考来源:

https://stackoverflow.com/questions/17812322/run-consecutive-commands-linux-with-java-runtime-exec

https://stackoverflow.com/questions/18866381/how-can-i-run-multiple-commands-in-just-one-cmd-windows-in-java

标签: java linux exec cmd

分享:

上一篇org.springframework.context.support.PostProcessorRegistrationDelegate$BeanPostProcessorChecker - Bean '' of type [] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)

下一篇JNI Demo in linux(在linux环境下的JNI示例程序)

关于我

崇尚极简,热爱技术,喜欢唱歌,热衷旅行,爱好电子产品的一介码农。

座右铭

当你的才华还撑不起你的野心的时候,你就应该静下心来学习,永不止步!

人生之旅历途甚长,所争决不在一年半月,万不可因此着急失望,招精神之萎葸。

Copyright 2015- 芒果酷(mangocool.com) All rights reserved. 湘ICP备14019394号

免责声明:本网站部分文章转载其他媒体,意在为公众提供免费服务。如有信息侵犯了您的权益,可与本网站联系,本网站将尽快予以撤除。