在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
數組中的命令。