Search code examples
javaprocessbuilder

ProcessBuilder not outputting the correct output


private void printNumberOfRecords(){
   try {
      ProcessBuilder builder = new ProcessBuilder(
         "/bin/sh", "-c",
         "grep", "\"target-word\"", localFileName, "|", "wc", "-l");
      Process p = builder.start();
      p.waitFor();
      BufferedReader br=new BufferedReader(
         new InputStreamReader(
            p.getInputStream()));
      String line;
      while(( line = br.readLine()) != null ) {
         System.out.println(line);
      }
   }
   catch( Exception e ) {
      e.printStackTrace();
   }
}

So I have the following code. The reads a file and counts the number of occurrences of a target word and prints the count. But when I run this function I don't see anything being printed.


Solution

  • Your code ask Java to wait until the subprocess sh end without reading the stream. When the buffer will be full, the subprocess wait, blocked.

    Don't use p.waitFor(); until you read the output. The output stream will be closed when the process end.

    To be complete, you have to check the error stream, too.

    As Andreas noticed, a try-with-resource will be better.