Java - 执行 Windows cmd 命令

Java - 执行 Windows cmd 命令

示例

import java.io.IOException;
import java.io.InputStream;

public class CmdExec {

    public static void main(String[] args) {
        Runtime runtime = Runtime.getRuntime();
        InputStream in = null;
        try {
            Process exec = runtime.exec("cmd.exe /c " + "tree /?"); // 执行 tree /? 命令
            in = exec.getInputStream(); // 获取执行结果
            
            int length = -1;
            byte[] buffer = new byte[1024];
            StringBuilder sb = new StringBuilder();
            
            while ((length = in.read(buffer)) != -1) {
                sb.append(new String(buffer, 0, length, "GBK"));
            }
            System.out.println(sb.toString());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

输出:

以图形显示驱动器或路径的文件夹结构。

TREE [drive:][path] [/F] [/A]

   /F   显示每个文件夹中文件的名称。
   /A   使用 ASCII 字符,而不使用扩展字符。

注意事项

需要注意的是,在示例中的第 18 行 sb.append(new String(buffer, 0, length, "GBK"));,字符串的字符集需要根据 cmd.exe 属性设置。否则,返回的结果可能是乱码。

在这里插入图片描述

在这里插入图片描述

参考

解决方案–java执行cmd命令ProcessBuilder–出错Exception in thread “main” java.io.IOException: Cannot run program “dir d:”: CreateProcess error=2(xjl456852原创)

发布了55 篇原创文章 · 获赞 0 · 访问量 3145

猜你喜欢

转载自blog.csdn.net/qq_29761395/article/details/104731485