Files.move() in Java giving a FilesSystemException error because folder is “being used by another process,” but it's not

ⅰ亾dé卋堺 提交于 2020-02-05 09:08:11

问题


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?


回答1:


Answer from user rollback:

Files.move(myFile.toPath(), myFolder.toPath().resolve(myFile.getName()), StandardCopyOption.REPLACE_EXISTING);



回答2:


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);
    }


来源:https://stackoverflow.com/questions/46595677/files-move-in-java-giving-a-filessystemexception-error-because-folder-is-bein

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!