在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
替換為相應的參數。注意,參數之間用空格分隔。