mouse-
mouse-

Reputation: 13

how to copy a file only if it does not exist in the to directory java

I have searched pretty thoroughly and I'm fairly certain that no one has asked this question. However, this may be because this is completely the wrong way to go about this. I once wrote an effective java program that copied files from one directory to another. If the file already existed in the corresponding directory it would be caught with an exception and renamed. I want to use this program for another application, and for this I want it to do nothing when the exception is caught, simply continue on with the program without copying that file. I will be using this to fix approximately 18gb of files when it works, if it even printed one character when the exception was caught it would be extremely inefficient. This is the code I have so far:

import java.nio.file.*;
import java.io.IOException;
public class Sync
{
    public static void main(String[] args)
    {
        String from=args[0];
        Path to=FileSystems.getDefault().getPath(args[1]);
        copyFiles(from, to);
    }
    public static void copyFiles(String from, Path to)
    {
        try(DirectoryStream<Path> files= Files.newDirectoryStream(FileSystems.getDefault().getPath(from)))
        {
            for(Path f:files)
            {
                Files.copy(f, to.resolve(f.getFileName()));
                System.out.println(" "+f.getFileName()+" copied ");
            }
        }
        catch(FileAlreadyExistsException e)
        {
            //not sure
        }
        catch(IOException e)
        {
            e.printStackTrace();
        }   
    }
}

Is there a way to use FileAlreadyExistsExcpetion to do this?

Upvotes: 0

Views: 3414

Answers (1)

Paolof76
Paolof76

Reputation: 909

I wouldn't use the try/catch to perform a user logic, this is wrong from a programming point of view and also not efficient. What I would do is to check if the file exists, and n that case skip the copy operation or do whatever you want

for(Path f:files)
{
   //here use Files.exists(Path path, LinkOption... options)
   Files.copy(f, to.resolve(f.getFileName()));
   System.out.println(" "+f.getFileName()+" copied ");
}

Here the Files docs: http://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html Good luck

Upvotes: 1

Related Questions