Move and replace file in a loop problem showing is being used by another process problem

196 Views Asked by At

I'm creating every time a file moving and replacing it from source folder to a destination folder with the same name in a loop and this is the problem :

For the first move and replace, it works well then it yells the process cannot access the file because it is being used by another process. when replacing the file in the destination folder and this is the method moving the file and replacing it every time

  public static void moveAndReplaceFile(String source, String destination) {
        try {
            Files.move(
                    Paths.get(source),
                    Paths.get(destination),
                    StandardCopyOption.REPLACE_EXISTING);
        } catch (IOException e) {
            LOGGER.error("Fail when moving and replacing");
        }
    }

can you help me guys? thanks in advance

2

There are 2 best solutions below

1
On

If its a network storage that you are using, then this can happen. As a workaround, you can try adding a sleep of 60seconds before executing the Files.Move API.

5
On

I suggest you to add the ATOMIC_MOVE option if supported :

public static void moveAndReplaceFile(String source, String destination) {
    try {
        Files.move(
                Paths.get(source),
                Paths.get(destination),
                StandardCopyOption.REPLACE_EXISTING, 
                StandardCopyOption.ATOMIC_MOVE);
    } catch (IOException e) {
        LOGGER.error("Fail when moving and replacing");
    }
}

See : https://docs.oracle.com/javase/tutorial/essential/io/move.html