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
		commands.add("ping");
        commands.add("localhost");
		commands.add("-4");
		executeProcess(commands);
		}
		catch (Exception exc) {
        System.out.println("error");
    }
    }

	static void executeProcess(List<String> commands){
		ProcessBuilder builder = new ProcessBuilder(commands);
		builder.redirectErrorStream(true);
        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) {
	            	break;
	            	}
	            System.out.println(line);
	        }
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
Advertisements

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s