Java 调用命令工具类

MyCmdUtil.java

import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.InputStreamReader;
/**
 * @Author : JCccc
 * @CreateTime : 2023/01/14
 * @Description :
 **/
@Slf4j
public class MyCmdUtil {

    public static void main(String[] args) {
        execCommand("echo \"Hello, World!\" >JcTest.txt");
    }


    /**
     * 执行并返回状态码
     *
     * @param cmd
     * @return
     */
    public static Boolean execCommand(String cmd) {


        BufferedReader br = null;
        try {
            boolean isWindows = System.getProperty("os.name").toLowerCase().startsWith("windows");
            String prefix1 = isWindows ? "cmd" : "/bin/sh";
            String prefix2 = isWindows ? "/c" : "-c";
            Process p = Runtime.getRuntime().exec(new String[]{prefix1, prefix2, cmd});
            // 0 表示正常
            int returnCode = p.waitFor();
            if (returnCode != 0) {
                br = new BufferedReader(new InputStreamReader(p.getErrorStream(),  isWindows ? "GB2312" : "UTF-8"));
                String line;
                StringBuilder sb = new StringBuilder();
                while ((line = br.readLine()) != null) {
                    sb.append(line).append("\n");
                }
                log.error("shell 执行失败: {}", sb);
                return false;
            }
            log.info("cmd = {}, returnCode = {}", cmd, returnCode);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

}

玩一下,简单用一下windows环境的命令试试:

    public static void main(String[] args) {
        execCommand("echo \"Hello, World!\" >JcTest.txt");
    }


看看效果:
Java 调用命令工具类_第1张图片

 

好了,就到这

你可能感兴趣的:(Java工具类,java大乱炖,java,调用命令)