Program to execute system commands in a Java

September 11, 2012 0 Comments

Most often in your Java programs you will find a need to execute system DOS commands. You can execute any system commands that are OS specific and then read the output of the system command from your Java program for further processing within the Java program.

This sample Java Program executes the 'dir' command reads the output of the dir command prints the results. This is just for understanding the concept, however, you may execute just about any command using this Runtime.getRuntime().exec() command.

Program to execute system commands in a Java

import java.io.*; 
public class TestCMD 
{ 
public static void main(String args[]) 
{ 
try 
{ 
Process p=Runtime.getRuntime().exec("cmd /c dir"); 
p.waitFor(); 
BufferedReader reader=new BufferedReader(new InputStreamReader(p.getInputStream())); 
String line=reader.readLine(); 
while(line!=null) 
{ 
System.out.println(line); 
line=reader.readLine(); 
} 
} 
catch(IOException e1) {} 
catch(InterruptedException e2) {} 

System.out.println("Done"); 
} 
} 

Program to execute system commands in a Java

Prakash Hari Sharma
I'm a software developer and Java enthusiast. I like clean and modular code, enjoy Agile projects and have a passion for trying out new things. I try to learn and teach every day, and occasionally I'm even able to blog about it. :)