I have a folder:

/Users/pavel/Desktop/test 

It has a sub /Users/pavel/Desktop/test/sub/ root.txt and a root.txt /Users/pavel/Desktop/test/root.txt file /Users/pavel/Desktop/test/root.txt I'm trying to copy the root.txt file to the sub folder. What would happen /Users/pavel/Desktop/test/sub/root.txt

I do this:

 File source = new File("/Users/pavel/Desktop/test/root.txt"); File dest = new File("/Users/pavel/Desktop/test/sub/root.txt"); dest.createNewFile(); Files.copy(source.toPath(), dest.toPath()); 

I fall with an error:

 java.nio.file.FileAlreadyExistsException: /Users/pavel/Desktop/test/sub/root.txt 

Although dest.createNewFile(); I did. Can you please tell me what am I doing wrong?

    2 answers 2

    The file /Users/pavel/Desktop/test/sub/root.txt already exists.

    Before creating a new file, check it for existence:

     if (!dest.exists()) { dest.createNewFile(); } 

      You can add a third parameter to the copy method — CopyOption . There is an option StandartCopyOption.REPLACE_EXISTING . If the file exists, it will be overwritten.

       File source = new File("/Users/pavel/Desktop/test/root.txt"); File dest = new File("/Users/pavel/Desktop/test/sub/root.txt"); Files.copy(source.toPath(), dest.toPath(), StandartCopyOption.REPLACE_EXISTING); 

      In general, do not do dest.createNewFile() , you can simply specify where to copy, and the file is automatically created.