4
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?

yoyosir
  • 458
  • 2
  • 11
  • 27
  • Would you please clarify what do you mean by realtime output vs. when command executes. You mean like listings that 'ls' produces vs completion code? – Edmon Aug 03 '12 at 03:13

3 Answers3

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.

Community
  • 1
  • 1
MvG
  • 57,380
  • 22
  • 148
  • 276
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

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

0

Actually, the problem is that Process.getInputStream() returns a BufferedReader. So, even if the called subprocess flushes all its output, a read in the calling Java program will only get it if the buffer is full.

Werner
  • 1