阅读量:2
在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 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替换为相应的参数。注意,参数之间用空格分隔。
以上就是关于“java exec 参数如何设置”的相关介绍,筋斗云是国内较早的云主机应用的服务商,拥有10余年行业经验,提供丰富的云服务器、租用服务器等相关产品服务。云服务器资源弹性伸缩,主机vCPU、内存性能强悍、超高I/O速度、故障秒级恢复;电子化备案,提交快速,专业团队7×24小时服务支持!
简单好用、高性价比云服务器租用链接:https://www.jindouyun.cn/product/cvm