gpt4 book ai didi

java - 从 Java 运行 .bat/.cmd 文件

转载 作者:搜寻专家 更新时间:2023-10-31 19:36:05 25 4
gpt4 key购买 nike

<分区>

我想从 Java 运行一个 .cmd 文件。我有一些对我有用的东西。有人可以帮助我了解我的程序可能出现的故障。

import java.io.IOException;  

/*
How to run a batch .bat or .cmd file from Java?
1. I don't want the command window to open up. It should be in background.
2. Gracefully destroy any new process created.
3. Need to confirm the quality of the program with experts.
*/
public class RunBat {
public static void main(String args[]) {
Runtime run = Runtime.getRuntime();
//The best possible I found is to construct a command which you want to execute
//as a string and use that in exec. If the batch file takes command line arguments
//the command can be constructed a array of strings and pass the array as input to
//the exec method. The command can also be passed externally as input to the method.

Process p = null;
String cmd = "D:\\Database\\TableToCSV.cmd";
try {
p = run.exec(cmd);
p.getErrorStream();
System.out.println("RUN.COMPLETED.SUCCESSFULLY");
}
catch (IOException e) {
e.printStackTrace();
System.out.println("ERROR.RUNNING.CMD");
p.destroy();
}
}
}

我的解决方案可靠吗?我如何才能确保在执行 .cmd 后没有进程挂起。

谢谢。

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com