Java执行系统命令

149 阅读2分钟

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;

/**
 * @author limaoxu
 * @date 2023/3/9 16:25
 */
public class ExecuteCMDTest {

    public static void main(String[] args) throws IOException, InterruptedException {
        String command = "dir";

        String[] cmd = new String[]{"cmd", "/c", command};
        String backupFilePath = "xxx";
        Process process = Runtime.getRuntime().exec(cmd);
        int i = process.waitFor();
        String inputStreamCharsetName = "GBK";
        if (i == 0) {
            // 0 表示线程正常终止
            System.out.println("执行成功!结果返回:");
            printInputStream(process.getInputStream(), inputStreamCharsetName);
        } else {

            printInputStream(process.getErrorStream(), inputStreamCharsetName);
        }
    }

    public static void printInputStream(InputStream inputStream, String charsetName){
        // 将InputStream赋值给变量inputStream
        //InputStream inputStream = System.in;

        // 创建一个BufferedReader对象,用于读取InputStream的字符流
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, Charset.forName(charsetName)));

        try {
            // 使用while循环读取输入流中的每一行内容,直到读取到结束符号
            String line;
            while ((line = reader.readLine()) != null) {
                // 将读取到的内容打印到控制台
                System.out.println(line);
            }
        } catch (IOException e) {
            // 出现IO异常时进行处理
            System.err.println("An error occurred: " + e);
        }
    }

}

执行结果:

执行成功!结果返回:
 驱动器 D 中的卷没有标签。
 卷的序列号是 B62B-C103

 D:\MyRepository\tdlib-java-demo 的目录

2023/03/09  16:39    <DIR>          .
2023/03/09  16:39    <DIR>          ..
2023/03/05  21:52                65 .gitignore
2023/03/10  11:02    <DIR>          .idea
2023/03/06  00:20               514 cmake-file.yml
2023/03/07  22:31    <DIR>          github-actions
2023/03/05  21:54    <DIR>          libs
2023/03/06  15:31    <DIR>          org.drinkless.tdlib
2023/03/05  15:08                 0 org.drinkless.tdlib.log
2023/03/07  14:54    <DIR>          org.drinkless.tdlib2
2023/03/07  14:55    <DIR>          org.drinkless.tdlib3
2023/03/09  20:02    <DIR>          org.drinkless.tdlib4
2023/03/05  15:14    <DIR>          out
2023/03/05  22:17               358 README.md
2023/03/05  15:06    <DIR>          src
2023/03/06  15:54               566 tdlib-java-demo.iml
               5 个文件          1,503 字节
              11 个目录 1,082,568,601,600 可用字节

Process finished with exit code 0