Execute batch script from Java

I had a requirement to do a Ping request to a server machine inside java and execute some batch scripts and get results. I found that native ping from java is bit difficult to implement and need some ground level work. Then I found the awesome ProcessBuilder class which can execute OS processes to achieve all my requirements in one implementation. Given below is a simple code for do a windows ping request using this class.

import java.util.ArrayList;
import java.util.List;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.IOException;

public class executeCmd {

    public static void main(String[] args) {
		try {
        List<String> commands = new ArrayList<String>();
        //simulate >ping localhost -4
		catch (Exception exc) {

	static void executeProcess(List<String> commands){
		ProcessBuilder builder = new ProcessBuilder(commands);
        Process p;
		try {
			p = builder.start();
	        BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream()));
	        BufferedWriter w = new BufferedWriter(new OutputStreamWriter(p.getOutputStream()));
	        String line;
	        while (true) {
	            line = r.readLine();
	            if (line == null) {
		} catch (IOException e) {
			// TODO Auto-generated catch block

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s