在Java中,你可以使用Runtime
类或ProcessBuilder
类来运行CMD命令
方法1:使用Runtime类
import java.io.BufferedReader; import java.io.InputStreamReader; public class RunCmdCommand { public static void main(String[] args) { try { String command = "cmd.exe /c dir"; // 这里可以替换为你想要运行的命令 Process process = Runtime.getRuntime().exec(command); BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream())); String line; while ((line = reader.readLine()) != null) { System.out.println(line); } process.waitFor(); reader.close(); } catch (Exception e) { e.printStackTrace(); } } }
方法2:使用ProcessBuilder类
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.Arrays; public class RunCmdCommand { public static void main(String[] args) { try { String[] command = {"cmd.exe", "/c", "dir"}; // 这里可以替换为你想要运行的命令 ProcessBuilder processBuilder = new ProcessBuilder(Arrays.asList(command)); processBuilder.redirectErrorStream(true); Process process = processBuilder.start(); BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream())); String line; while ((line = reader.readLine()) != null) { System.out.println(line); } process.waitFor(); reader.close(); } catch (Exception e) { e.printStackTrace(); } } }
这两个示例都会运行cmd.exe /c dir
命令,该命令会列出当前目录下的所有文件和文件夹。你可以根据需要修改command
数组中的命令。