How to redirect Process Builder's output to a string?

Ankesh Anand picture Ankesh Anand · May 23, 2013 · Viewed 91.5k times · Source

I am using the following code to start a process builder.I want to know how can I redirect its output to a String.

ProcessBuilder pb = new ProcessBuilder(System.getProperty("user.dir")+"/src/generate_list.sh", filename);
Process p = pb.start();

I tried using ByteArrayOutputStream but it didn't seem to work.

Answer

Reimeus picture Reimeus · May 23, 2013

Read from the InputStream. You can append the output to a StringBuilder:

BufferedReader reader = 
                new BufferedReader(new InputStreamReader(process.getInputStream()));
StringBuilder builder = new StringBuilder();
String line = null;
while ( (line = reader.readLine()) != null) {
   builder.append(line);
   builder.append(System.getProperty("line.separator"));
}
String result = builder.toString();