0

I want to copy a file from one folder to another using java , but the second folder contains a file which has the same name as the file I want to copy.

So how would I do this?

I tried to rename the file after I copy it but this didn't work and the file didn't even appear. Please suggestions!

I was trying to copy using this line of code

FileUtils.copyFileToDirectory(newFile, dir);

sara
  • 1

1 Answers1

1

this is a way of solution, rename destFile if exist some file with the same name in dest directory, it add the string "copy" in the end of path (you can change the added string)

private static void copyFile(File source, File dest) {
    while (dest.exists()) {
        dest = new File(dest.getPath() + "copy");
    }
    try {
        Files.copy(source.toPath(), dest.toPath());
    } catch (IOException e) {
        e.printStackTrace();
    }
}
  • Hello! You can format your code by either indenting all lines with 4 spaces, or by surrounding the block in triple backticks \`\`\` (like in Markdown) – YellowAfterlife Sep 26 '19 at 16:43
  • You should give a secured exit condition to your while loop, like a counter that stops at 1000 or whatever value sits you. – Thomas Martin Sep 27 '19 at 02:56