2

I want to move a single file to another folder, but I can't because "it is being used by another process." This is my code:

static File myFile = new File("C:\\filepath");
static File myFolder = new File("C:\\folderpath");

public static void main(String[] args) 
        throws IOException {
    fileMove();
}

public static void fileMove() 
        throws IOException {
    Files.move(myFile.toPath(), myFolder.toPath(), StandardCopyOption.REPLACE_EXISTING);
    return;
}

Error message:
Exception in thread "main" java.nio.file.FileSystemException: C:\folderpath: The process cannot access the file because it is being used by another process.

I've tried out different files, different folders, but everytime it says the file is being used. I've tested it with a basic text file that was definitely closed and not being used when I tested it, but I still get the error. Does anyone know what's going on? Or, is there another way to move files that won't have this issue?

Display name
  • 95
  • 1
  • 2
  • 12
  • Possible duplicate of [java.nio.file.FileSystemException: The process cannot access the file because it is being used by another process](https://stackoverflow.com/questions/33924479/java-nio-file-filesystemexception-the-process-cannot-access-the-file-because-it) – alzee Oct 05 '17 at 22:37
  • 3
    `Files.move(myFile.toPath(), myFolder.toPath().resolve (myFile.getName ()), StandardCopyOption.REPLACE_EXISTING);` – Felix Oct 05 '17 at 22:41
  • @alzee That solution did not give an error, but the file was not moved at all. – Display name Oct 05 '17 at 22:42
  • @rollback We have a winner! This fixes my problem. Thank you. – Display name Oct 05 '17 at 22:46

2 Answers2

0

Answer from user rollback:

Files.move(myFile.toPath(), myFolder.toPath().resolve(myFile.getName()), StandardCopyOption.REPLACE_EXISTING);
Display name
  • 95
  • 1
  • 2
  • 12
  • 1
    Didn't have the time to post a full answer, that's why I added it as an comment. Explanation: The second argument of `Files.move(Path, Path, CopyOption...)` has to be the destination path (including the destination filename). That's why you had to add `.resolve(myFile.getName())` – Felix Oct 06 '17 at 15:09
-1

I use:

public static void moveFile(String origen, String destino) throws IOException {
        Path FROM = Paths.get(origen);
        Path TO = Paths.get(destino);

        CopyOption[] options = new CopyOption[]{
            StandardCopyOption.ATOMIC_MOVE

        };
        Files.move(FROM, TO, options);
    }