在Java中,可以使用Runtime.exec()
方法或ProcessBuilder
类来执行外部命令
Runtime.exec()
方法:try {
String command = "your_command_here"; // 例如: "notepad.exe" 或 "ipconfig"
Process process = Runtime.getRuntime().exec(command);
// 等待命令执行完成
int exitCode = process.waitFor();
System.out.println("Command executed with exit code: " + exitCode);
} catch (IOException e) {
System.err.println("Error executing command: " + e.getMessage());
} catch (InterruptedException e) {
System.err.println("Command execution was interrupted: " + e.getMessage());
}
ProcessBuilder
类:try {
List<String> command = new ArrayList<>();
command.add("your_command_here"); // 例如: "notepad.exe" 或 "ipconfig"
command.add("arg1"); // 添加参数,例如: "C:\\Users\\username\\Documents"
command.add("arg2"); // 添加参数,例如: "example.txt"
ProcessBuilder processBuilder = new ProcessBuilder(command);
Process process = processBuilder.start();
// 等待命令执行完成
int exitCode = process.waitFor();
System.out.println("Command executed with exit code: " + exitCode);
} catch (IOException e) {
System.err.println("Error executing command: " + e.getMessage());
} catch (InterruptedException e) {
System.err.println("Command execution was interrupted: " + e.getMessage());
}
在这两个示例中,将your_command_here
替换为您要执行的外部命令,将arg1
和arg2
替换为相应的参数。注意,参数之间用空格分隔。