Executing 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

If you get the answer to it,please let me know.

Thanking you in advance.

-- Tapan Sanghvi (tapan_sanghvi@yahoo.com), December 05, 2001.


try this

//copy 1 text file to 2 text //java BRRead firstfile.txt secondfile.txt import java.io.*;

class BRRead{ public static void main(String args[]) throws IOException{ int i; FileInputStream fin; FileOutputStream fout; try{ try{ fin = new FileInputStream(args[0]); }catch(FileNotFoundException e){ System.out.println("Input file not found"); return; } try{ fout = new FileOutputStream(args[1]); }catch(FileNotFoundException e){ System.out.println("Output file not found"); return; } }catch(ArrayIndexOutOfBoundsException e){ System.out.println("Usage:CopyFile From To "); return; } try{ do{ i=fin.read(); if(i!=-1)fout.write(i); }while(i!=-1); }catch(IOException e){ System.out.println("File error"); } fin.close(); fout.close(); }}

-- Val (jzelinsky@mail.ru), January 24, 2002.


Well this method is good but time consuming.. what id i need to move an entire directory..in such cases running system commands is faster.. so please can any one help me out.. i have problem while running it in a JSP

-- Tushar (tushar_s2@yahoo.com), July 24, 2002.

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

-- prashant a. (p_ashar@hotmail.com), July 25, 2002.

Moderation questions? read the FAQ