更新时间:2023-12-03 23:23:16
利用 ProcessBuilder
。
它可以更容易地构建流程参数并解决在命令中自动包含空格的问题...
It makes it easier to build the process parameters and takes care of issues with having spaces in commands automatically...
public class TestProcessBuilder {
public static void main(String[] args) {
try {
ProcessBuilder pb = new ProcessBuilder("cmd", "/c", "dir");
pb.redirectError();
Process p = pb.start();
InputStreamConsumer isc = new InputStreamConsumer(p.getInputStream());
isc.start();
int exitCode = p.waitFor();
isc.join();
System.out.println("Process terminated with " + exitCode);
} catch (IOException | InterruptedException exp) {
exp.printStackTrace();
}
}
public static class InputStreamConsumer extends Thread {
private InputStream is;
public InputStreamConsumer(InputStream is) {
this.is = is;
}
@Override
public void run() {
try {
int value = -1;
while ((value = is.read()) != -1) {
System.out.print((char)value);
}
} catch (IOException exp) {
exp.printStackTrace();
}
}
}
}
我通常构建一个通用类,您可以通过命令(例如dir)及其参数传递,它会自动将调用附加到操作系统。如果命令允许输入,我还可以通过监听器回调接口甚至输入来获取输出的能力......
I'd generally build a all purpose class, which you could pass in the "command" (such as "dir") and it's parameters, that would append the call out to the OS automatically. I would also included the ability to get the output, probably via a listener callback interface and even input, if the command allowed input...