Tuesday, May 10, 2011

Java - Copying one file to another

Here is function called copyFile  which takes 2 strings – source and destination. It copies source to destination.

 

private static void copyFile(String srcFile, String dstFile){

try{

File f1 = new File(srcFile);

File f2 = new File(dstFile);

InputStream in = new FileInputStream(f1);

//Append the file
OutputStream out = new FileOutputStream(f2,true);
//Overwrite the file.
OutputStream out = new FileOutputStream(f2);


byte[] buf = new byte[1024];

int len;

while ((len = in.read(buf)) > 0){

out.write(buf, 0, len);

}

in.close();

out.close();

System.out.println("File copied.");

}

catch(FileNotFoundException ex){

System.out.println(ex.getMessage() + " in
the specified directory."
);
return false;

}

catch(IOException e){

System.out.println(e.getMessage());
return false;

}
return true;
}

No comments:

Post a Comment

Chitika