我正在尝试在Process()
函数中使用命令时读取来自终端的响应。我看过其他例子,但我无法让它工作。例如,我无法处理数据并使用进度条,因此我需要在数据出现在终端时访问它。在我的代码中,我只是使用 textArea 来查看它现在是否有效。我可以在 Eclipse 的控制台中看到数据,但 textArea 中没有出现任何内容。我究竟做错了什么?
public void unPack(String filePath, String directory)
{
ProcessBuilder pb = new ProcessBuilder("/usr/local/bin/unrar", "x", "-y",filePath);
pb.inheritIO();
pb.directory(new File(directory));
try
{
final Process p = pb.start();
BufferedReader in = new BufferedReader(
new InputStreamReader(p.getInputStream()));
String line = null;
while ((line = in.readLine()) != null) {
textArea.setText(line);
}
try
{
int exitVal = p.waitFor();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
自己运行命令时mac终端的响应结果是:
UNRAR 4.20 freeware Copyright (c) 1993-2012 Alexander Roshal
Extracting from testrar.part1.rar
Extracting testfile.mkv 23%
Extracting from testrar.part2.rar
... testfile.mkv 46%
Extracting from testrar.part3.rar
... testfile.mkv 70%
Extracting from testrar.part4.rar
... testfile.mkv 93%
Extracting from testrar.part5.rar
... testfile.mkv OK
All OK