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?

1
  • 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? Commented Aug 3, 2012 at 3:13

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.