0

I am doing a simple program for copy my file from existing directory to another directory, I had tested two difference set of syntax which are

Files.copy(sour, Dest, StandardCopyOption.REPLACE_EXISTING);

and

Files.move(sour, Dest.resolve(sour.getFileName()));

But both of them fail to function as expected because I wish to replace any similar file name which already exist in the directory.

Files.move(sour, Dest.resolve(sour.getFileName()));

will able to copy the file to new directory for the first time but when it's try to copy the second time with the same file name, a FileAlreadyExist exception being throw out. I can't open the file and read the file, after that rewrite to another file in difference location, because it's will also contain .exe file or .zip file

This is the source code

String sour1 = "Z://folder//";
String sourPath = sour1.concat(fileName);
try
{
    Path sour = Paths.get(sourPath);
    Path Dest = Paths.get("C://Users");
    System.out.println("Start to copy file");
    // Files.move(sour, Dest.resolve(sour.getFileName()));
    Files.copy(sour, Dest, StandardCopyOption.REPLACE_EXISTING);
try-catch-finally
  • 7,436
  • 6
  • 46
  • 67
attack
  • 103
  • 1
  • 11
  • 1
    Possible duplicate of [Is this the best way to rewrite the content of a file in Java?](http://stackoverflow.com/questions/1016278/is-this-the-best-way-to-rewrite-the-content-of-a-file-in-java) – Meyer Dec 06 '16 at 07:51
  • i cant rewrite the file content, let say if the user upload .zip file or .exe file, it's cant rewrite the content – attack Dec 06 '16 at 07:58
  • replace your Dest path with this and try. Path Dest = Paths.get("C://Users", sour .getFileName().toString()); and sour with this Path sour = Paths.get(sour1,fileName); – Darshit Dec 06 '16 at 08:16

0 Answers0