Java Copy Directory Examples

Today I will show you three java examples that copy the source directory with it’s content to the target directory.

1. Use Java IO To Copy Directory.

  1. This example uses the traditional java File and Input / Output Stream class to implement the copy directory process. You can see code comments for more detail.
    public void copyDirectory(String srcDir, String destDir)
    {
    	try
    	{
    		// Create source object.
    		File srcDirFile = new File(srcDir);
    			
    		// Create destination object. 
    		File destDirFile = new File(destDir);
    			
    		/* Only copy exist directory. */
    		if(srcDirFile.exists())
    		{
    			if(srcDirFile.isDirectory())
    			{
    				/* If destination directory is not exist then create it. */
    				if(!destDirFile.exists())
    				{
    					destDirFile.mkdirs();
    					System.out.println("Target Directory " + destDirFile + " dose not exist, create it.");
    				}
    				
    				/* Get source directory sub-content. */
    				File[] srcDirSubFileArr = srcDirFile.listFiles();
    				
    				/* Loop in the directory sub content. */
    				for(File srcDirSubFile : srcDirSubFileArr)
    				{
    					/* Get subfile name. */
    					String subFileName = srcDirSubFile.getName();
    					
    					/* Create source subfile and target subfile. */
    					File subSrcFile = new File(srcDirFile, subFileName);
    					File subDestFile = new File(destDirFile, subFileName);
    					
    					/* Copy recursively. */
    					copyDirectory(subSrcFile.getCanonicalPath(), subDestFile.getCanonicalPath());
    					
    					System.out.println("Recursive copy from " + subSrcFile.getCanonicalPath() + " to " + subDestFile.getCanonicalPath());
    				}
    				
    			}else
    			{
    				/* If source is a file. */
    				this.copyFile(srcDirFile, destDirFile);
    			}
    		}
    	}catch(Exception ex)
    	{
    		ex.printStackTrace();
    	}
    }
    
    
    /* Copy data from source to target. * */
    public void copyFile(File srcFile, File destFile) throws IOException
    {
    	/* Create buffered input stream to improve read speed. */
    	InputStream srcInput = new FileInputStream(srcFile);
    	BufferedInputStream srcBis = new BufferedInputStream(srcInput);
    	
    	/* Create buffered output stream to improve write speed. */
    	OutputStream destOutput = new FileOutputStream(destFile);
    	BufferedOutputStream destBos = new BufferedOutputStream(destOutput);
    	
    	byte byteBufferArr[] = new byte[1024];
    	
    	/* Read byte data to buffer, if all data has been read then readLen==-1. */
    	int readLen = srcBis.read(byteBufferArr);
    	
    	while(readLen>0)
    	{
    		destBos.write(byteBufferArr);
    		readLen = srcBis.read(byteBufferArr);
    	}
    	
    	/* Do not forget flush output stream buffer and close both input and output buffer stream.*/
    	destBos.flush();
    	destBos.close();
    	destOutput.close();
    	
    	srcBis.close();
    	srcInput.close();
    	
    	System.out.println("Copy successful from " + srcFile.getCanonicalPath() + " to " + destFile.getCanonicalPath());
    }
    

2. Use Apache Commons IO.

  1. Go to Apache commons-io download page.
  2. Download the latest version.
  3. After download, extract the zip file to a local folder. Then add commons-io-2.5.jar to your java project as below. You can read How to add selenium server standalone jar into your java project to learn how to add a jar in the java project.
  4. Java example code.
    /* Use Apache commons io to copy directory. 
     * srcDirPath : Source folder path.
     * destDirPath : Target folder path.
     * fileExtension : If empty then copy all, if specified then only copy those extension file, such as "exe", "txt" etc.
     * */
    public void copyWithApacheCommonsIO(String srcDirPath, String destDirPath, String fileExtension)
    {
    	try
    	{
    		File srcDir = new File(srcDirPath);
    		File destDir = new File(destDirPath);
    		
    		if("".equals(fileExtension))
    		{
    			/* Copy all. */
    			/* Will create destDir automatically if destDir dose not exist. */
    			FileUtils.copyDirectory(srcDir, destDir);
    		}else
    		{
    			/* Copy special extension file. */
    			
    			/* Create a special extension filter.*/		
    			IOFileFilter fileExtensionFilter = FileFilterUtils.suffixFileFilter(fileExtension);
    			
    			/* Use and(IOFileFilter ... fileFilter) method to declare a filter that only copy those extension file, such as "exe", "txt".
    			 * The and method three-dot means the method parameter can be zero or more IOFileFilter object, or a IOFileFilter array.
    			 * */
    			IOFileFilter fileFilter = FileFilterUtils.and(FileFileFilter.FILE, fileExtensionFilter);
    				
    			/* Use or(IOFileFilter ... fileFilter) method to tell FileUtils copy either directory or specified extension file just created. */
    			FileFilter fileAndDirFilter = FileFilterUtils.or(DirectoryFileFilter.DIRECTORY, fileFilter);
    
    			// Copy using the filter
    			FileUtils.copyDirectory(srcDir, destDir, fileAndDirFilter);
    		}
    			
    		System.out.println(srcDirPath + " has been copied to " + destDirPath + " successfully. ");
    	}catch(Exception ex)
    	{
    		ex.printStackTrace();
    	}
    }
    

3. Use Java New IO.

  1. Create a File visitor class first, this visitor will be invoked during java new io’s Files.walkFileTree() method. The below file JavaNewIOCopyFileVisitor.java is an example.
    public class JavaNewIOCopyFileVisitor extends SimpleFileVisitor {
    	
    	private String srcDir;
    	
    	private String destDir;
    
    	public String getSrcDir() {
    		return srcDir;
    	}
    
    	public void setSrcDir(String srcDir) {
    		this.srcDir = srcDir;
    	}
    
    	public String getDestDir() {
    		return destDir;
    	}
    
    	public void setDestDir(String destDir) {
    		this.destDir = destDir;
    	}
    
    	@Override
    	public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes arg1) throws IOException {
    		/* Get both source and destination directory Path object. */
    		Path srcPath = Paths.get(this.getSrcDir());
    		Path destPath = Paths.get(this.getDestDir());
    		
    		/* Get the relative Path object between source and current directory. */
    		Path relativePath = srcPath.relativize(dir);
    		
    		/* Get the target directory Path instance. */
    		Path targetDirPath = destPath.resolve(relativePath);
    		
    		try {
    			/* Copy current go through directory to target directory, replace target if exist. */
                Files.copy(dir, targetDirPath, StandardCopyOption.REPLACE_EXISTING);
            } catch (FileAlreadyExistsException ex) {
                 if (!Files.isDirectory(targetDirPath))
                     throw ex;
            }
    		
    		return FileVisitResult.CONTINUE;
    	}
    
    	@Override
    	public FileVisitResult visitFile(Path file, BasicFileAttributes arg1) throws IOException {
    		/* Get both source and destination directory Path object. */
    		Path srcPath = Paths.get(this.getSrcDir());
    		Path destPath = Paths.get(this.getDestDir());
    		
    		/* Get Path object that current file relative to source folder. */
    		Path relativeFilePath = srcPath.relativize(file);
    		
    		/* Use the relative path to get target folder Path object. */
    		Path targetFilePath = destPath.resolve(relativeFilePath);
    
    		/* Copy current file to target file, replace target if exist. */
    		Files.copy(file, targetFilePath, StandardCopyOption.REPLACE_EXISTING);
    		
    		return FileVisitResult.CONTINUE;
    	}
    }
    
  2. Copy use java new io code example.
    /* Copy source directory to target directory use java new io. */
    public void copyWithJavaNewIO(String srcDir, String destDir)
    {
    	try
    	{	
    		/* First create a file visitor object which will be invoked when go through each file or directory. */
    		JavaNewIOCopyFileVisitor copyFileVisitor = new JavaNewIOCopyFileVisitor();
    		copyFileVisitor.setSrcDir(srcDir);
    		copyFileVisitor.setDestDir(destDir);
    		
    		/* Create the root copy Path object. */
    		Path srcPath = Paths.get(srcDir);
    		
    		/* Walk through each file or directory under the root path.*/
    		Files.walkFileTree(srcPath, copyFileVisitor);
    		
    		System.out.println(srcDir + " has been copied to " + destDir + " successfully. ");
    	}catch(Exception ex)
    	{
    		ex.printStackTrace();
    	}
    }
    

4. Difference Between Java IO and Apache Commons IO.

  1. Apache Commons IO provides more useful classes with advanced features.
  2. Apache Commons IO and Java IO copy speed are not too much different.
  3. Below is the java main method, we have record the two copy methods used time. The source directory is about 4 Gigabyte, we can see two methods used time is nearly the same.
    public static void main(String[] args) {
    	
    	CopyDirectoryExample cde = new CopyDirectoryExample();
    	
    	/* Below code will copy only .exe file from source to target folder. */
    	cde.copyWithApacheCommonsIO("C:/WorkSpace/DreamWeaver", "C:/WorkSpace/DreamWeaver_bak", "exe");
    	
    	long startTime = 0;
    	long endTime = 0;
    	
    	startTime = System.currentTimeMillis();
    	cde.copyDirectory("C:/WorkSpace/dev2qa.com", "C:/WorkSpace/dev2qa.com_bak_1");
    	endTime = System.currentTimeMillis();
    	long deltaTime = endTime - startTime;
    	System.out.println("copyDirectory(String srcDir, String destDir) use time " + deltaTime);
    	
    	startTime = System.currentTimeMillis();
    	cde.copyWithApacheCommonsIO("C:/WorkSpace/dev2qa.com", "C:/WorkSpace/dev2qa.com_bak_2", "");
    	endTime = System.currentTimeMillis();
    	deltaTime = endTime - startTime;
    	System.out.println("copyWithApacheCommonsIO(String srcDir, String destDir) use time " + deltaTime);
    
    	startTime = System.currentTimeMillis();
    	cde.copyWithJavaNewIO("C:/WorkSpace/dev2qa.com", "C:/WorkSpace/dev2qa.com_bak_nio");
    	endTime = System.currentTimeMillis();
    	deltaTime = endTime - startTime;
    	System.out.println("copyWithJavaNewIO(String srcDir, String destDir) use time " + deltaTime);
    }
  4. Below are the two methods copyDirectory(String srcDir, String destDir) and copyWithApacheCommonsIO(String srcDir, String destDir) used time comparison.
    Recursive copy from C:\WorkSpace\dev2qa.com\Zhao Song English_Resume.doc to C:\WorkSpace\dev2.com\Zhao Song English_Resume_1.doc
    copyDirectory(String srcDir, String destDir) use time 396303
    C:\WorkSpace\dev2qa.com has been copiea to C:\WorkSpace\dev2qa.com_bak_2 successfully.
    copyWithApacheCommonsIO(String srcDir, String destDir) use time 390880

References

  1. Apache Commons IO Java Doc

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.