Monday, May 11, 2009

How to use Runtime.getRuntime().exec, How to solve, error 2, Use Dos command in Java

This below code is very perfect to use Runtime.getRuntime().exec in windows platform as well as unix platform. You will not get ioexception error2 using this code.

Here, there are three method. Out of these first two you can put in common java file. Three is calling method to execute any dos commnad.

public Boolean exec(String[] command) {
Process proc;
StringBuffer cmdStr= new StringBuffer();
for(int i=0; icmdStr.append(command[i].trim());
cmdStr.append(" ");
try {
proc = Runtime.getRuntime().exec(cmdStr.toString());
} catch (IOException e) {
System.out.println("EXCEPTION_IO" + command);
System.out.println("EXCEPTION_TRACE"+ e);
return new Boolean(false);
int exitStatus;
while (true) {
try {
exitStatus = proc.waitFor();
} catch (java.lang.InterruptedException e) {
System.out.println("EXCEPTION_TRACE"+ e);
if (exitStatus == 0) {
InputStream is = proc.getInputStream();
if (exitStatus != 0) {
InputStream e = proc.getErrorStream();
String error = readStreamData(e);
System.out.println("ERROR_COMMAND"+ error);
return new Boolean(exitStatus == 0);

private static String readStreamData(InputStream e) {
BufferedInputStream bre = new BufferedInputStream(e);
String output = new String(" ");
try {
int readInt =;
while (readInt != -1) {
char c = (char) readInt;
output = output + c;
readInt =;
} catch (IOException e1) {
return output;

public void copyFile(){
String sourceFile = "c:\\abcd\\mainImage\\DSC01596.JPG";
String destFile = "C:\\BackupImage\\Home";
List command = new ArrayList();
System.out.println("Executing Command :: " + command);
if(exec((String[]) command.toArray(new String[1]))){
System.out.println("Copied Successfully");
System.out.println("Some Problem during copy");


  1. I am making a project in java which contains comapring images and see whether the are same and i want to know how will i start with it.

    even i want to implement barcode system in please help.

  2. hi binod,
    Thanks lot ,this has given an idea to me ....i could build and run successfully the code which does copying from source to destination ..but I'm getting run time exceptions for image comparision using imagemagick in java..could u please send me the code which does image comparision in java to

  3. i cant understand that how i can insert this code in jsp or servlet pages ..plz help me sir


Please put your feedback or your any question related to this blog. Thanks.