How to Execute System Commands from a Java Program : LUSENET : Java Programming : One Thread

I want to copy an existing file to a non-existing file. I know that Runtime class in java.lang package will execute the system commands. Following is the code I have written.

import java.lang.*;

public class nui { public static void main(String args[]) { try { Runtime rt=Runtime.getRuntime(); Process p=rt.exec("copy c:\\christa\\a1.txt c:\\christa\\a2.txt"); p.waitFor(); System.out.println("process"+p.exitValue()); } catch(Exception e) { System.out.println(e.getMessage()); } } }

But, it ends with an exception like this. CreateProcess: copy c:\christa\a1.txt c:\christa\a2.txt error=2

Can anybody help me out regarding this.

Thanks in advance.


-- Selvi Christa (, September 25, 2001


error=2 is following the classic Unix ERRNO values -- it means "File Not Found".

The problem is that the runtime cannot find the "copy" command you want to execute.

The reason is because "copy" is not a stand-alone program, like "format" or "fdisk", it is part of the DOS command shell.

To execute that, you would have to say:

Process p=rt.exec("C:\\command /c copy c:\\christa\\a1.txt etc.");

What you are doing there is executing the DOS command prompt (note that this is for Windows 95, and 98 -- for NT it would be just "cmd" and I have no idea about ME), and passing to it the option /c meaning execute the following command.


-- NetSlut (, October 11, 2001.

Earlier the answer for this question was given as

Process p=rt.exec("C:\\command /c copy c:\\christa\\a1.txt etc.");

by somebody else, but still it was not working .

so it is better to use the following one

Process p=rt.exec("command /c copy c:\\christa\\a1.txt etc."); for winodows 98

and for widows nt try the following one

Process p=rt.exec("cmd /c copy c:\\christa\\a1.txt etc.");

-- yuvaraj (, November 27, 2001.

i have tested it.both of them can't work out.

but i think if u wrap the copy command and call it from the will be ok.

-- cuiqi (, October 31, 2002.

Hi Christa, try this works on windows 98.

class ex { public static void main(String a[]) { String cmdLine="start command /c copy c:\\user.txt c:\\user1.txt"; try { Process p = Runtime.getRuntime().exec(cmdLine);

} catch(IOException ioe){System.out.println(ioe);}

} }

-- sumathy (, January 31, 2003.

This code works in NT. import*;

public class dload { public static void main(String arg[]) { Process p = null; Runtime rt; try { rt = Runtime.getRuntime(); p=rt.exec("cmd /c copy d:\\java-collections\\ d:\\newdir"); } catch(Exception e) { System.out.println(e); } } }

-- Karthikeyan D (, April 10, 2003.

Moderation questions? read the FAQ