runCmdOnDir是指定目录执行的函数
package cn.com.ruijie.rgonc.grpc.impl.utils;

import java.io.*;

public class CommandUtil {
    public static void runCMD(String[] CMD) {
        java.lang.Process process = null;
        try {
            process = Runtime.getRuntime().exec(CMD);
            ByteArrayOutputStream resultOutStream = new ByteArrayOutputStream();
            InputStream errorInStream = new BufferedInputStream(process.getErrorStream());
            InputStream processInStream = new BufferedInputStream(process.getInputStream());
            int num = 0;
            byte[] bs = new byte[1024];
            while ((num = errorInStream.read(bs)) != -1) {
                resultOutStream.write(bs, 0, num);
            }
            while ((num = processInStream.read(bs)) != -1) {
                resultOutStream.write(bs, 0, num);
            }
            String result = new String(resultOutStream.toByteArray(), "gbk");
            System.out.println(result);
            errorInStream.close();
            processInStream.close();
            resultOutStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (process != null) process.destroy();
        }
    }

    public static void runCmdOnDir(String[] CMD, String path) {
        java.lang.Process process = null;
        try {
            process = Runtime.getRuntime().exec(CMD, null, new File(path));
            ByteArrayOutputStream resultOutStream = new ByteArrayOutputStream();
            InputStream errorInStream = new BufferedInputStream(process.getErrorStream());
            InputStream processInStream = new BufferedInputStream(process.getInputStream());
            int num = 0;
            byte[] bs = new byte[1024];
            while ((num = errorInStream.read(bs)) != -1) {
                resultOutStream.write(bs, 0, num);
            }
            while ((num = processInStream.read(bs)) != -1) {
                resultOutStream.write(bs, 0, num);
            }
            String result = new String(resultOutStream.toByteArray(), "gbk");
            System.out.println(result);
            errorInStream.close();
            processInStream.close();
            resultOutStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (process != null) process.destroy();
        }
    }
}

 

相关文章:

  • 2022-12-23
  • 2021-08-21
  • 2021-04-13
  • 2022-12-23
  • 2021-12-23
  • 2022-01-29
  • 2021-08-13
  • 2022-12-23
猜你喜欢
  • 2021-04-08
  • 2021-04-03
  • 2021-10-19
  • 2022-01-31
  • 2022-12-23
  • 2022-01-29
相关资源
相似解决方案