How to Run System Command and Read Its Output in Java


In this example, we will demonstrate how to run operating system specific command and read its output.

Source Code

package com.beginner.examples;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
 
public class RunCommandExample {
 
    public static void main(String a[]){
      
        // new ProcessBuilder
        ProcessBuilder pb = new ProcessBuilder("ping","Yahoo.com");
        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