Monday, May 11, 2009

How to use Runtime.getRuntime().exec, How to solve java.io.IOException, 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());
if(i!=command.length-1){
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();
break;
} catch (java.lang.InterruptedException e) {
System.out.println("EXCEPTION_TRACE"+ e);
}
}
if (exitStatus == 0) {
InputStream is = proc.getInputStream();
readStreamData(is);
}
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 = bre.read();
while (readInt != -1) {
char c = (char) readInt;
output = output + c;
readInt = bre.read();
}
} catch (IOException e1) {
e1.printStackTrace();
}
return output;
}


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

3 comments:

  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.

    ReplyDelete
  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 sindhu.aspire87@gmail.com

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

    ReplyDelete

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