Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to redirect ProcessBuilder's output to a string?

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.

like image 211
Ankesh Anand Avatar asked May 23 '13 12:05

Ankesh Anand


People also ask

What is a processbuilder redirect in Java?

The type of a ProcessBuilder.Redirect. Indicates that subprocess I/O source or destination will be the same as those of the current process. Indicates that subprocess I/O will be connected to the current Java process over a pipe. Returns a redirect to append to the specified file.

How do I start a process from a processbuilder?

Process process = new ProcessBuilder ( "java", "-version" ).start (); First, we create our ProcessBuilder object passing the command and argument values to the constructor. Next, we start the process using the start () method to get a Process object.

What is the use of redirect in subprocess?

Returns a redirect to write to the specified file. Returns the type of this Redirect. Indicates that subprocess I/O will be connected to the current Java process over a pipe. This is the default handling of subprocess standard I/O.

What is processbuilder API in Java?

1. Overview The Process API provides a powerful way to execute operating system commands in Java. However, it has several options that can make it cumbersome to work with. In this tutorial, we'll take a look at how Java alleviates that with the ProcessBuilder API. 2. ProcessBuilder API


4 Answers

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();
like image 159
Reimeus Avatar answered Oct 09 '22 09:10

Reimeus


Using Apache Commons IOUtils you can do it in one line:

ProcessBuilder pb = new ProcessBuilder("pwd");
String output = IOUtils.toString(pb.start().getInputStream(), StandardCharsets.UTF_8);
like image 41
Daniel Avatar answered Oct 09 '22 08:10

Daniel


As of Java 9, we finally have a one liner:

ProcessBuilder pb = new ProcessBuilder("pwd");
Process process = pb.start();

String result = new String(process.getInputStream().readAllBytes());
like image 22
kmecpp Avatar answered Oct 09 '22 09:10

kmecpp


Java 8 example:

public static String runCommandForOutput(List<String> params) {
    ProcessBuilder pb = new ProcessBuilder(params);
    Process p;
    String result = "";
    try {
        p = pb.start();
        final BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));

        StringJoiner sj = new StringJoiner(System.getProperty("line.separator"));
        reader.lines().iterator().forEachRemaining(sj::add);
        result = sj.toString();

        p.waitFor();
        p.destroy();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return result;
}

Usage:

List<String> params = Arrays.asList("/bin/sh", "-c", "cat /proc/cpuinfo");
String result = runCommandForOutput(params);

I use this exact code and it works well for single or multiple line results. You could add an error stream handler as well.

like image 11
Greg T Avatar answered Oct 09 '22 10:10

Greg T