要从 java 在 bash 中执行进程/命令,可以使用以下类:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Arrays;
public class CmdExecutor {
public CmdExecutor(){
}
public void exe(String [] args) throws IOException{
if (args.length <= 0) {
System.out.println("empty command");
return;
}
Process process = new ProcessBuilder(args).start();
InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;
System.out.printf("Output of running %s is:",
Arrays.toString(args));
while ((line = br.readLine()) != null) {
System.out.println(line);
}
}
}
然而。如果进程没有终止(还)怎么办。它进行计算并将其输出到外壳中。我希望能够在另一个线程中运行该进程并获取输出中的更改,例如逐帧字符串。如何做到这一点?