Jacob
Jacob

Reputation: 383

Copying files with Java

I'm attempting to copy a file from one location to another while replacing the older file and I keep getting this error: The method copy(Path, Path, CopyOption...) in the type Files is not applicable for the arguments (File, File, StandardCopyOption)

My code is as follows

Files.copy(file1, file2, StandardCopyOption.REPLACE_EXISTING);

I've also tried using this method:

CopyOption[] options = new CopyOption[]{
  StandardCopyOption.REPLACE_EXISTING
}; 
Files.copy(file1, file2, options[0]);

And I get this error: The method copy(Path, Path, CopyOption...) in the type Files is not applicable for the arguments (File, File, CopyOption)

Any thoughts?

Upvotes: 1

Views: 4202

Answers (4)

lriostavira
lriostavira

Reputation: 9

have you tried casting the StandardCopyOption?

Try:

    CopyOption co = (CopyOption) StandardCopyOption.REPLACE_EXISTING;

Based on the error you are getting, it seems to me that you are using files even though the method Files.copy() uses Inputstream or Path, not Files.

This may be a duplicate of Copy file in Java and replace existing target

Hope this helps. Good Luck Have Fun :)

Upvotes: -1

user4184746
user4184746

Reputation:

You Should not use Files. Instead of that use paths.

Files.copy(file1.toPath(), file2.toPath(), StandardCopyOption.REPLACE_EXISTING);

Upvotes: 0

Bathsheba
Bathsheba

Reputation: 234875

Judging by the helpful error message, file1 and file2 are File objects.

But you need to pass Path objects to the copy method.

So you need to use

Files.copy(file1.toPath(), file2.toPath(), StandardCopyOption.REPLACE_EXISTING);

instead.

Upvotes: 1

M A
M A

Reputation: 72884

You need to pass Path objects, not Files:

Files.copy(file1.toPath(), file2.toPath(), StandardCopyOption.REPLACE_EXISTING);

Upvotes: 3

Related Questions