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();
}
}

}

Advertisements
  1. No trackbacks yet.

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

%d bloggers like this: