Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy file in Java and replace existing target

I'm trying to copy a file with java.nio.file.Files like this:

Files.copy(cfgFilePath, strTarget, StandardCopyOption.REPLACE_EXISTING); 

The problem is that Eclipse says "The method copy(Path, Path, CopyOption...) in the type Files is not applicable for the arguments (File, String, StandardCopyOption)"

I'm using Eclipse and Java 7 on Win7 x64. My project is set up to use Java 1.6 compatibility.

Is there a solution to this or do I have to create something like this as a workaround:

File temp = new File(target);  if(temp.exists())   temp.delete(); 

Thanks.

like image 605
commander_keen Avatar asked Jun 18 '13 13:06

commander_keen


People also ask

How to duplicate files in java?

If you are working on Java 7 or higher, you can use Files class copy() method to copy file in java. It uses File System providers to copy the files.

How do I edit an existing file in java?

As proposed in the accepted answer to a similar question: open a temporary file in writing mode at the same time, and for each line, read it, modify if necessary, then write into the temporary file. At the end, delete the original and rename the temporary file.

What is StandardCopyOption Replace_existing?

public static final StandardCopyOption REPLACE_EXISTING. Replace an existing file if it exists.


1 Answers

You need to pass Path arguments as explained by the error message:

Path from = cfgFilePath.toPath(); //convert from File to Path Path to = Paths.get(strTarget); //convert from String to Path Files.copy(from, to, StandardCopyOption.REPLACE_EXISTING); 

That assumes your strTarget is a valid path.

like image 138
assylias Avatar answered Oct 05 '22 00:10

assylias