Run Simple DOS Command from java program

Some of us might have question that can we really run DOS command from our own java program? Yes it is true we can do that. For that we need Process class.

Below is the sample program to run the simple dir command from java program


import java.io.*;

public class RunDosCommands
{
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");
}
}

That's it you know the drill. Type the program in your editor. Save it as RunDosCommands.java. and run the class file.

Folks, remember it will print the list of directory where the class file is running. For Ex, if the class file is running from C directory it will print all the directory list of your C drive.

2 comments: