Friday, July 8, 2011

Java Code to execute DOS Commands

/*

Note : Even you have set your JDK path in Environment variable, Set it using command prompt prior executing this code

Program will give your output in MyOutput.txt file at the same location where program is.

*/

import java.io.*;

public class ExecDosCmd
{

public static void main(String rk[])
{
Process p = null;
Runtime rt;
String line = null;
int i=0;

try
{
FileOutputStream file=new FileOutputStream("MyOutput.txt");
rt = Runtime.getRuntime();
p=rt.exec("cmd /c dir");
BufferedReader br = new BufferedReader (new InputStreamReader(p.getInputStream()));
while((i=br.read())!=-1)
{
file.write((char)i);
}

} catch(Exception e)
{
System.out.println(e);
}
}
}

No comments:

Post a Comment