Click here to Skip to main content
15,885,896 members
Articles / Programming Languages / Java
Tip/Trick

Copy Modified Files

Rate me:
Please Sign up or sign in to vote.
5.00/5 (1 vote)
9 Sep 2016CPOL1 min read 9.5K   3
Copy the modified files from one directory to another

Introduction

This is a tip to guide you on how we can copy the updated files from one folder to another folder.

Background

I recently had one requirement where I needed to copy the files from one location to another location by last modified date. So for example in Source Location Folder “A" and Target location Folder "B".

Whenever some process puts the files in my A folder, my program should copy only the new files. With every run, it should not include the files which have been already considered/copied in the last run.

I have been through many articles, but did not find the best solution, so I wrote some code and wanted to share it so that it can be utilized by larger audiences.

Using the Code

I created one class FilesCopy. In this class, there are 3 methods:

  1. Main method from where there is an entry point into the program from where we made the call to another method called GetFiles.
  2. GetFiles method takes 2 arguments and Get all the files from the source folder A. It mainly does 2 things:
    1. A. It checks if this a first time copy, then it copies all the files from source to target folder.
    2. B. If it is not the first time, then it goes and checks each file in source location if there is a new file added (checks by using the file attributes). It copies it to the target location and skips the already copied files.

    This GetFiles method calls another method copyFile to perform the copy.

  3. copyFile takes the 2 arguments source file and target location as an input and copies the files to target location.
Java
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

public class FilesCopy
{
    public static void main(String[] args)
    {
        File srcFolder = new File("c:\\temp");
        File destFolder = new File("c:\\Temp1");

        try {
            GetFiles(srcFolder,destFolder);
        } catch (IOException e) {
              System.out.println(e.getMessage());
              System.out.println(e.getStackTrace());
        }
     }    
    
   public static void copyFile(File src, File dest) throws IOException 
   {
       InputStream in = null ;
       OutputStream out = null;
       try{
            in = new FileInputStream(src);
            out = new FileOutputStream(dest);
    
           byte[] buffer = new byte[32*1024];
    
           int length;
           //copy the file content in bytes
           while ((length = in.read(buffer)) > 0){
              out.write(buffer, 0, length);
           }
       }
      catch(IOException e){
          System.out.println(e.getMessage());
          System.out.println(e.getStackTrace());
      }
       
       finally {
           in.close();
           out.close();
       }
   }    

    public static void GetFiles(File src, File dest)
        throws IOException{

        Date destLastModified =  new Date(dest.lastModified());       
        
        if(src.isDirectory()){

            //if directory not exists, create it
            if(!dest.exists()){
               dest.mkdir();
               System.out.println("Target Directory Does not exists Created a New directory :: "
                              +  dest);
            }
                        
            List<File> filesInFolder  = Files.walk(Paths.get(src.toURI()))
                    .filter(Files::isRegularFile)
                    .map(Path::toFile)
                    .collect(Collectors.toList());
            
            if(dest.list().length > 0)
            {
                Date sourceLastModified = null;
                System.out.println("Checking the Modified Files in the source Directory");
                for(File file : filesInFolder)
                {
                    Path path = Paths.get(file.getAbsolutePath());
                    
                    //Here reading the file creation date
                    sourceLastModified = new Date(Files.readAttributes
                    (path, BasicFileAttributes.class).creationTime().toMillis());
                    
                    //System.out.println("Modified Files are ....");
                    if( sourceLastModified.after(destLastModified))
                    {
                        System.out.println("Modified File is " + file.getName());
                        File destFile = new File(dest, file.getName());
                        copyFile(file, destFile);
                        
                        System.out.println("Copied the file  " +file  + " to " + destFile);
                    }
                }
            }
            else{
                
                System.out.println("No file in the target folder coping all the file from source");
                for(File file : filesInFolder)
                {
                    File srcFile = new File(src, file.getName());
                    File destFile = new File(dest, file.getName());
                    copyFile(srcFile,destFile);
                    System.out.println("Copied the file  " + srcFile  + " to " + destFile);
                }
            }            
        }
    }
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionProblems with code? Pin
Member 1255206412-Sep-16 15:43
Member 1255206412-Sep-16 15:43 
AnswerRe: Problems with code? Pin
dileep15-Sep-16 6:50
dileep15-Sep-16 6:50 
GeneralRe: Problems with code? Pin
Member 1255206419-Sep-16 3:41
Member 1255206419-Sep-16 3:41 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.