温馨提示×

java exec 参数如何设置

小樊
82
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