简体   繁体   中英

Copy files from one directory to another and append new files with timestamp instead of overwriting in Java

I want to copy files from source directory to destination. If the file already exists in the destination directory, then append the new file to be copied with its timestamp so that there is no overwrite. How do I check for duplicates and append timestamp to the new file name? Please help!

public static void copyFolder(File src, File dest)
    throws IOException{
        //list all the directory contents
        String files[] = src.list();
        for (String file : files) {
           //construct the src and dest file structure
           File srcFile = new File(src, file);
           File destFile = new File(dest, file);
           //recursive copy
           copyFolder(srcFile,destFile);
        }
    }else{
        //if file, then copy it
        //Use bytes stream to support all file types
        InputStream in = new FileInputStream(src);
            OutputStream out = new FileOutputStream(dest);
            byte[] buffer = new byte[1024];
        int length;
            //copy the file content in bytes
            while ((length = in.read(buffer)) > 0){
               out.write(buffer, 0, length);
            }

            in.close();
            out.close();
            System.out.println("File copied from " + src + " to " + dest);
    }
}

You can check if the file exists using File.exist() method, if exists, you can open the file in the append mode

The code is something like this

File f = new File(oldName);
if(f.exists() && !f.isDirectory()) { 
    long currentTime=System.currentTimeMillis();
    String newName=oldName+currentTime;
    // do the copy

}
    //construct the src and dest file structure
    File srcFile = new File(src, file);
    File destFile = new File(dest, file);
    while (destFile.exists()) {
        destFile = new File(dest, file + '-' + Instant.now());
    }

In one case the destination file got named test-file.txt-2018-03-14T11:05:21.103706Z . The time given is in UTC. In any case you will end up with a name of file that doesn't already exist (if the loop terminates, but I have a hard time seeing the scenario where it doesn't).

You may want to append the timestamp only to plain files and reuse existing folders (directories), I don't know your requirements here. And you may want to append the timestamp before the extension if there is one (to get test-file-2018-03-14T11:05:21.103706Z.txt instead). I trust you to make the necessary modifications.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM