db-jdo-dev mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From Craig L Russell <craig.russ...@oracle.com>
Subject Recursive File Copy - Java - Source Code | DreamInCode.net
Date Fri, 01 Oct 2010 16:25:18 GMT
Hi Michelle,

Take a look at this.


  * This function will copy files or directories from one location to  
  * note that the source and the destination must be mutually  
exclusive. This
  * function can not be used to copy a directory to a sub directory of  
  * The function will also have problems if the destination files  
already exist.
  * @param src -- A File object that represents the source for the copy
  * @param dest -- A File object that represnts the destination for  
the copy.
  * @throws IOException if unable to copy.
public static void copyFiles(File src, File dest) throws IOException {
	//Check to ensure that the source is valid...
	if (!src.exists()) {
		throw new IOException("copyFiles: Can not find source: " +  
	} else if (!src.canRead()) { //check to ensure we have rights to the  
		throw new IOException("copyFiles: No right to source: " +  
	//is this a directory copy?
	if (src.isDirectory()) 	{
		if (!dest.exists()) { //does the destination already exist?
			//if not we need to make it exist if possible (note this is mkdirs  
not mkdir)
			if (!dest.mkdirs()) {
				throw new IOException("copyFiles: Could not create direcotry: " +  
dest.getAbsolutePath() + ".");
		//get a listing of files...
		String list[] = src.list();
		//copy all the files in the list.
		for (int i = 0; i < list.length; i++)
			File dest1 = new File(dest, list[i]);
			File src1 = new File(src, list[i]);
			copyFiles(src1 , dest1);
	} else {
		//This was not a directory, so lets just copy the file
		FileInputStream fin = null;
		FileOutputStream fout = null;
		byte[] buffer = new byte[4096]; //Buffer 4K at a time (you can  
change this).
		int bytesRead;
		try {
			//open the files for input and output
			fin =  new FileInputStream(src);
			fout = new FileOutputStream (dest);
			//while bytesRead indicates a successful read, lets write...
			while ((bytesRead = fin.read(buffer)) >= 0) {
		} catch (IOException e) { //Error copying file...
			IOException wrapper = new IOException("copyFiles: Unable to copy  
file: " +
						src.getAbsolutePath() + "to" + dest.getAbsolutePath()+".");
			throw wrapper;
		} finally { //Ensure that the files are closed (if they were open).
			if (fin != null) { fin.close(); }
			if (fout != null) { fout.close(); }
Craig L Russell
Architect, Oracle
408 276-5638 mailto:Craig.Russell@oracle.com
P.S. A good JDO? O, Gasp!

  • Unnamed multipart/alternative (inline, None, 0 bytes)
View raw message