溫馨提示×

java exec 參數如何設置

小樊
132
2024-12-03 08:30:10
欄目: 編程語言

在Java中,可以使用Runtime.exec()方法或ProcessBuilder類來執行外部命令

  1. 使用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());
}
  1. 使用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替換為您要執行的外部命令,將arg1arg2替換為相應的參數。注意,參數之間用空格分隔。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女