How to Run ProcessBuilder with a Command List in Java


In this example we will show how to run ProcessBuilder with a command list in Java.

Source Code

package com.beginner.examples;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
 
public class RunCommandListExample {
 
    public static void main(String a[]){
         
        List commandList = new ArrayList();
        commandList.add("ls");
        commandList.add("-all");
        commandList.add("/");
        // new ProcessBuilder
        ProcessBuilder pb = new ProcessBuilder(commandList);
        try 
        {
            // start ProcessBuilder
        	Process p = pb.start();
            InputStream in = p.getInputStream();
            byte[] b = new byte[1024];
            int size = 0;
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            while((size = in.read(b)) != -1){
            	out.write(b, 0, size);
            }
            System.out.println(new String(out.toByteArray()));
            in.close();
            out.close();
        } 
        catch (IOException e) 
        {
            e.printStackTrace();
        }
    }
}

Output:

Pinging Yahoo.com [72.30.35.9] with 32 bytes of data:
Reply from 72.30.35.9: bytes=32 time=226ms TTL=47
Reply from 72.30.35.9: bytes=32 time=226ms TTL=47
Reply from 72.30.35.9: bytes=32 time=223ms TTL=47

Ping statistics for 72.30.35.9:
    Packets: Sent = 3, Received = 3, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
    Minimum = 223ms, Maximum = 226ms, Average = 225ms

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments