How to Execute System Commands from a Java Program

greenspun.com : 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.

Christa

-- Selvi Christa (selvichrista@chennai.tcs.co.in), September 25, 2001

Answers

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

-- NetSlut (netslut@nightisland.com), 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 (yuva@lycos.com), 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 java.it will be ok.

-- cuiqi (cui_qi0@21cn.com), October 31, 2002.


Hi Christa, try this code.it 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 (sumathy.ka@tatainfotech.com), January 31, 2003.


This code works in NT. import java.io.*;

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\\dload.java d:\\newdir"); } catch(Exception e) { System.out.println(e); } } }

-- Karthikeyan D (karthik.durai@siritech.com), April 10, 2003.



Moderation questions? read the FAQ