I have 2 folders, each containing dozens of batch files (*.bat
).
The batch files containing text similar to either
del /f/q F:\\MEDIA\\IMAGE99
Uses Apache Commons-IO
package com.stackoverflow.windows;
import java.io.File;
import org.apache.commons.io.IOUtils;
import org.apache.commons.io.output.NullOutputStream;
public class Command {
private Command() {}
public static boolean batch(File file) {
boolean handled = false;
Process process = null;
ProcessBuilder pb = new ProcessBuilder("cmd", "/c", file.getAbsolutePath());
pb.redirectErrorStream(true);
try {
process = pb.start();
IOUtils.copy(process.getInputStream(), new NullOutputStream());
handled = process.waitFor() == 0;
} catch (Exception ignore) {
// Only throws an IOException we're trying to avoid anyway,
// and an expected InterruptedException
// handled will be false
} finally {
if (process != null) {
IOUtils.closeQuietly(process.getInputStream());
}
}
return handled;
}
}
now the output hangs at
waitFor()
When you start an external process from Java using Runtime.exec
you must read any output that the process produces otherwise the process may block (source: JavaDocs for java.lang.Process).
Use ProcessBuilder
instead, and call redirectErrorStream
to merge the standard output and error streams, then read all the content from process.getInputStream()
until you reach EOF. Only then is it safe to call waitFor
.
ProcessBuilder will also help with the spaces issue, as you must split up the command line into individual words yourself
ProcessBuilder pb = new ProcessBuilder("cmd", "/c", file.getAbsolutePath());