Java 程序在调用批处理文件之前退出
Java program exits before the batch file is invoked
我编写了一个简单的 java 程序来调用批处理文件。问题是,当我运行 这个Java 程序没有任何反应时,批处理文件没有被执行。但是当我在调试模式下逐行执行同一个程序时,批处理文件就会被执行。
我怀疑这里的问题是我的 JVM 在我的进程实际完成之前就关闭了。我可以输入 Thread.sleep() 但我不想这样做。
有没有其他方法可以让我的进程完成然后 JVM 关闭。
public static void main(String[] args) {
String batchFilePath = "D:\MyDir";
String batchFileName = "callMe.bat";
executeBatchFile(batchFilePath, batchFileName);
}
public static void executeBatchFile(String filePath, String fileName) {
try {
List cmdAndArgs = Arrays.asList("cmd", "/c", fileName);
ProcessBuilder pb = new ProcessBuilder(cmdAndArgs);
pb.directory(new File(filePath));
Process p = pb.start();
} catch (Exception e) {
e.printStackTrace();
}
您可以使用 ProcessBuilder 的 waitFor 方法来等待启动的进程完成。这是来自 javadocs
的 waitFor
的描述
Causes the current thread to wait, if necessary, until the process
represented by this Process object has terminated. This method returns
immediately if the subprocess has already terminated. If the
subprocess has not yet terminated, the calling thread will be blocked
until the subprocess exits.
我编写了一个简单的 java 程序来调用批处理文件。问题是,当我运行 这个Java 程序没有任何反应时,批处理文件没有被执行。但是当我在调试模式下逐行执行同一个程序时,批处理文件就会被执行。
我怀疑这里的问题是我的 JVM 在我的进程实际完成之前就关闭了。我可以输入 Thread.sleep() 但我不想这样做。 有没有其他方法可以让我的进程完成然后 JVM 关闭。
public static void main(String[] args) {
String batchFilePath = "D:\MyDir";
String batchFileName = "callMe.bat";
executeBatchFile(batchFilePath, batchFileName);
}
public static void executeBatchFile(String filePath, String fileName) {
try {
List cmdAndArgs = Arrays.asList("cmd", "/c", fileName);
ProcessBuilder pb = new ProcessBuilder(cmdAndArgs);
pb.directory(new File(filePath));
Process p = pb.start();
} catch (Exception e) {
e.printStackTrace();
}
您可以使用 ProcessBuilder 的 waitFor 方法来等待启动的进程完成。这是来自 javadocs
的waitFor
的描述
Causes the current thread to wait, if necessary, until the process represented by this Process object has terminated. This method returns immediately if the subprocess has already terminated. If the subprocess has not yet terminated, the calling thread will be blocked until the subprocess exits.