1

I am trying to run the below command from java and want to capture the output. The method is getting completed immediately without writing anything to the console.

Linux Command is repo forall -c 'echo pwd is;pwd;git status' and the method is

public static String executeCommandWithOutput(String command) {
    System.out.println("Running the command "+command);
    StringBuffer output = new StringBuffer();
    String line = "";
    try {
        Process process =Runtime.getRuntime().exec(command);
        process.waitFor();

        BufferedReader reader = 
            new BufferedReader(new InputStreamReader(process.getInputStream()));
        while ((line = reader.readLine())!= null) {
            output.append(line);
        }
        System.out.println("Content is "+output.toString());
    } catch (IOException e) {
        e.printStackTrace();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    return output.toString();
}

I tried redirecting the output to a file as well. Neither worked. Any thoughts??

Bhargav Kumar R
  • 2,190
  • 3
  • 22
  • 38
  • this link might also be helpful: http://stackoverflow.com/questions/14165517/processbuilder-forwarding-stdout-and-stderr-of-started-processes-without-blocki – nafas Sep 18 '15 at 11:49
  • If you call `waitFor` first, the process will finish and there won't be any output to read. Call `waitFor` *after* you've read the output. – VGR Sep 18 '15 at 15:21

1 Answers1

1

Check if the command your are trying to execute has a standard output.

Probably its failing and you are getting error output.

You can check the error output with getErrorStream, documentation is here.

E.g. like this

StringBuffer error = new StringBuffer();

BufferedReader reader = 
    new BufferedReader(new InputStreamReader(process.getErrorStream()));

while ((line = reader.readLine())!= null) {
        error.append(line);
}

System.out.println("Error is " + error.toString());

Also check the exitValue of your forked command, doc is here

int exitStatus = process.exitValue();

System.out.println("Exit status is " + exitStatus );
deimus
  • 9,565
  • 12
  • 63
  • 107
  • yes.. It is throwing the error 'echo: -c: line 0: unexpected EOF while looking for matching `'''. But when i run the same command from linux terminal it is executing! – Bhargav Kumar R Sep 18 '15 at 11:54