1

public class test {

private static void copyGABuild(){
     try {
         String loc = "C:\\Users\\KAG\\Desktop\\\\test";
         
         Files.copy(Paths.get(loc), Paths.get("C:\\Users\\KAG\\Desktop"));
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

public static void main(String[] args) {
    
    
    copyGABuild();

}

I am getting this error 'java.nio.file.FileAlreadyExistsException' C:\Users\KAG\Desktop

I dont want to use FileUtils to copy, is there any way I can achieve this using Files. And there is no file inside the directory C:\Users\KAG\Desktop. but it still says FileAlreadyExistsException

tala d
  • 109
  • 2
  • 7

2 Answers2

1

According to this link, the copy method accepts a REPLACE_EXISTING parameter, which solves your problem.

You can implement this as follows:

Files.copy(Paths.get(loc), Paths.get("C:\\Users\\KAG\\Desktop"), StandardCopyOption.REPLACE_EXISTING)

Give this a shot!

EDIT:

See docs:

REPLACE_EXISTING – Performs the copy even when the target file already exists. If the target is a symbolic link, the link itself is copied (and not the target of the link). If the target is a non-empty directory, the copy fails with the FileAlreadyExistsException exception.

I left a comment for your problem, if this is the case. Good luck!

arkantos
  • 497
  • 3
  • 14
  • there is no file inside C:\Users\KAG\Desktop, but it still saying file exists – tala d Feb 04 '21 at 15:34
  • is C:\Users\KAG\Desktop empty?, if so can you create a dummy file inside it, and rerun your code? Does it run succesfully now? – arkantos Feb 04 '21 at 15:44
0

The problem is that Files.copy is specified as unambiguous as possible. Hence you need to specify the target to be created/overwritten.

For a file that would be:

Files.copy(Paths.get(loc), Paths.get("C:\\Users\\KAG\\Desktop\\test"));

The mistake: a directory is copied without content! Javadoc:

If the file is a directory then it creates an empty directory in the target location

This method can be used with the walkFileTree method to copy a directory and all entries in the directory, or an entire file-tree where required.

However Files also has Stream methods for directory walks. Take care to createDirectories of subdirectories.

Joop Eggen
  • 107,315
  • 7
  • 83
  • 138