Running DOS command using java!
Hi…
Here is a small example.
We can use to run a dos command using java code.
/***************Code ******************/
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
class SunilCmd {
static public void main(String args[]) {
try {
StringBuffer sb = new StringBuffer();
BufferedReader buff = new BufferedReader(new InputStreamReader( Runtime.getRuntime().exec(“cmd.exe /C dir”).getInputStream()));
/* Here Runtime.getRuntime creates environment to run the command */
/* .exec executes the parameters given inside the method */
/*
* here “cmd.exe /C” will invoke the DOS in exclusive mode and “dir”
* is a command that will be executed…..
*/
String line = buff.readLine();
while (line != null) {
sb.append(line + “\n”);
line = buff.readLine();
}
System.out.println(sb);
File f = new File(“output.txt”);
/**
*All the output will be written into output.txt file
*/
FileOutputStream fos = new FileOutputStream(f);
fos.write(sb.toString().getBytes());
fos.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
No trackbacks yet.