public static void executeCommand(String cmd) {
try {
Process process = Runtime.getRuntime().exec(cmd, null,
new File("/usr/hadoop-0.20.2/"));
InputStream stdin = process.getInputStream();
InputStreamReader isr = new InputStreamReader(stdin);
BufferedReader br = new BufferedReader(isr);
String line;
System.out.println("<output></output>");
while ((line = br.readLine()) != null)
System.out.println(line);
InputStreamReader esr = new InputStreamReader(
process.getErrorStream());
BufferedReader errorReader = new BufferedReader(esr);
String lineError;
while ((lineError = errorReader.readLine()) != null)
System.out.println(lineError);
process.waitFor();
System.out.println("");
} catch (Exception e) {
e.printStackTrace();
}
}
Here's my code for executing a command named 'cmd'. But I cannot get realtime output through this code. The output comes out when the command finishes. I want realtime output. Is there a way to do this?
这是我执行名为'cmd'的命令的代码。但我无法通过此代码获得实时输出。命令完成后输出结果。我想要实时输出。有没有办法做到这一点?
2 个解决方案
#1
3
The issue you describe is most likely caused by the application you called: many applications use unbuffered I/O when connected to a terminal, but bufferen I/O when connected to a pipe. So your cmd
may simply decide not to write its output in small bits, but instead in huge chunks. The proper fix is to adjust the command, to flush its output at the appropriate times. There is little you can do about this on the Java side. See also this answer.
您描述的问题很可能是由您调用的应用程序引起的:许多应用程序在连接到终端时使用无缓冲的I / O,但在连接到管道时会使用I / O.因此,您的cmd可能只是决定不以小位写入其输出,而是以巨大的块为单位。正确的解决方法是调整命令,在适当的时间刷新其输出。在Java方面你几乎无能为力。另见这个答案。
#2
0
I think you need to have a thread for handling the output.
我认为你需要一个线程来处理输出。
You should try first with the cmd which run for a while
你应该先尝试运行一段时间的cmd
Last time, when I try with wvdial command (this wvdial will not finish until we stop it), I need a thread to read the output of wvdial
上次,当我尝试wvdial命令(这个wvdial将不会完成,直到我们停止它),我需要一个线程来读取wvdial的输出
#1
3
The issue you describe is most likely caused by the application you called: many applications use unbuffered I/O when connected to a terminal, but bufferen I/O when connected to a pipe. So your cmd
may simply decide not to write its output in small bits, but instead in huge chunks. The proper fix is to adjust the command, to flush its output at the appropriate times. There is little you can do about this on the Java side. See also this answer.
您描述的问题很可能是由您调用的应用程序引起的:许多应用程序在连接到终端时使用无缓冲的I / O,但在连接到管道时会使用I / O.因此,您的cmd可能只是决定不以小位写入其输出,而是以巨大的块为单位。正确的解决方法是调整命令,在适当的时间刷新其输出。在Java方面你几乎无能为力。另见这个答案。
#2
0
I think you need to have a thread for handling the output.
我认为你需要一个线程来处理输出。
You should try first with the cmd which run for a while
你应该先尝试运行一段时间的cmd
Last time, when I try with wvdial command (this wvdial will not finish until we stop it), I need a thread to read the output of wvdial
上次,当我尝试wvdial命令(这个wvdial将不会完成,直到我们停止它),我需要一个线程来读取wvdial的输出