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");
    }


効果を見てみましょう:

 

はい、行きます

おすすめ

転載: blog.csdn.net/qq_35387940/article/details/131561005