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 属性设置。否则,返回的结果可能是乱码。