我正在制作一个自动测试CLI的程序。我遇到的一个部分是从命令行读取输出。我的代码如下所示:
private static File createTempScript(List<String> commands) throws IOException {
final File tempScript = File.createTempFile("script", null);
final Writer streamWriter = new OutputStreamWriter(new FileOutputStream(
tempScript));
final PrintWriter printWriter = new PrintWriter(streamWriter);
for(String command: commands) {
printWriter.println(command);
}
printWriter.close();
return tempScript;
}
/**
* Takes in a list of commands that then get sent to make a script. After the script is created this method will
* then run the script.
*/
public void executeCommand(List<String> commands) throws IOException {
final File tempScript = createTempScript(commands);
final ProcessBuilder pb = new ProcessBuilder("bash", tempScript.toString());
final Process process = pb.start();
final BufferedReader in = new BufferedReader(new
InputStreamReader(process.getInputStream()));
final BufferedReader out = new BufferedReader(new
InputStreamReader(process.getInputStream()));
String s;
while ((s = in.readLine()) != null) {
if(!s.isEmpty())
{
Output.add(s);
}
}
}
我现在遇到的问题是,在while循环中,只要它到达我需要在命令中输入的行,程序就会挂起。每当我注释掉那个循环时,程序运行正常。
感谢您的帮助。