public static void copyFile ( String src, String dest, boolean overwrite, boolean createDestDir ) throws IOException {
File fS = new File( src);
if ( !fS.exists()) throw new IOException( "Source file <" + src + "> does not exist");
if ( !fS.canRead()) throw new IOException( "Source file <" + src + "> unreadable");
File fD = new File( dest);
if ( fD.exists()) {
if (!fD.isFile()) throw new IOException( "Destination file <" + dest + "> is a directory");
if (!overwrite) throw new IOException( "Destination file <" + dest + "> already exists");
fD.delete();
}
File pDir = getParentDir( fD);
boolean pDirExists = pDir.exists();
if (!pDirExists) {
if (createDestDir) {
// create all needed parent directories
pDir.mkdirs();
}else{
throw new IOException( "Destination directory <" + pDir + "> does not exist");
}
}
if (!pDir.canWrite()) throw new IOException( "Destination directory <" + pDir + "> not writable");
FileInputStream fis = new FileInputStream( fS);
FileOutputStream fos = new FileOutputStream( fD);
byte[] buf = new byte[1024];
int bytesRead;
while (true) {
bytesRead = fis.read( buf);
if ( bytesRead == -1) break;
fos.write( buf, 0 , bytesRead);
}
fis.close();
fos.flush();
fos.close();
}