skip to main | skip to sidebar

Java Programs and Examples with Output

Pages

▼
 
  • RSS
  • Twitter
Tuesday, October 9, 2012

Copy source file/directory to destination file/directory

Posted by Raju Gupta at 1:05 PM – 0 comments
 
This function will copy files or directories from one location to another.
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 itself. 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.
First check is this a directory copy? If so then does the destination already exist? If not try to create the directory or report error.
If the directory already exists or has been successfully created then get the list of files in source directory to destination.
If the source was not a directory then create a buffer and copy source file to destination file.
public static void copyFiles(File src, File dest) throws IOException 
{
 if (!src.exists()) 
 {
  throw new IOException("copyFiles: Can not find source: " + src.getAbsolutePath()+".");
 }
 else if (!src.canRead()) 
 { 
  throw new IOException("copyFiles: No right to source: " + src.getAbsolutePath()+".");
 }
 
 if (src.isDirectory()) 
 {
  if (!dest.exists()) 
  { 
   if (!dest.mkdirs()) 
   {
    throw new IOException("copyFiles: Could not create direcotry: " + dest.getAbsolutePath() + ".");
   }
  }
  
  String list[] = src.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 
 { 
  FileInputStream fin = null;
  FileOutputStream fout = null;
  byte[] buffer = new byte[4096];
  int bytesRead;
  try 
  {
   
   fin =  new FileInputStream(src);
   fout = new FileOutputStream (dest);
   
   while ((bytesRead = fin.read(buffer)) >= 0) 
   {
    fout.write(buffer,0,bytesRead);
   }
  } 
  catch (IOException e) 
  {
   IOException wrapper = new IOException("copyFiles: Unable to copy file: " + 
      src.getAbsolutePath() + "to" + dest.getAbsolutePath()+".");
   wrapper.initCause(e);
   wrapper.setStackTrace(e.getStackTrace());
   throw wrapper;
  }
  finally 
  { 
   if (fin != null) { fin.close(); }
   if (fout != null) { fin.close(); }
  }
 }
}

Labels: Copy File Example , Java Input Output Example

Leave a Reply

Newer Post Older Post
Subscribe to: Post Comments ( Atom )
  • Popular
  • Recent
  • Archives
Powered by Blogger.
 
 
 
© 2011 Java Programs and Examples with Output | Designs by Web2feel & Fab Themes

Bloggerized by DheTemplate.com - Main Blogger