java Cannot delete file, being used by another process

你说的曾经没有我的故事 提交于 2019-12-18 09:04:35

问题


I have this code

 import org.apache.commons.io.FileUtils;
    try {
        FileUtils.copyURLToFile(new URL(SHA1_LINK), new File("SHA1.txt"));
        if(!sameSha1()) {
            System.out.println("sha diferentes");
            FileUtils.copyURLToFile(new URL(LINK), new File(PROG));
        }
    } catch (Exception e) {
        System.out.println("Internet is off");
    }
    //delete SHA1 file
    Files.deleteIfExists(Paths.get("SHA1.txt"));

and when I execute it it says

java.nio.file.FileSystemException
The process cannot access the file because it is being used by another process (in sun.nio.fs.WindowsException)

In the sameSha1() I have this:

String sha1Txt = new Scanner(new File("SHA1.txt")).useDelimiter("\\Z").next();

I want to delete the file 'SHA1.txt'. How can I do this?


回答1:


I guess with sameSha1 you open SHA1.txt to read it and you forget to close it.

EDIT:

From your comment you contain the following line in sameSha1:

String sha1Txt = new Scanner(new File("SHA1.txt")).useDelimiter("\\Z").next();

So you create a scanner instance but you don't explicitly close it. You should do something like that:

Scanner s = new Scanner(new File("SHA1.txt"));
try {
    String sha1Txt = s.useDelimiter("\\Z").next();
    ...
    return result;
}
finally {
    s.close();
}

Or as @HuStmpHrrr suggests in Java 7:

try(Scanner s = new Scanner(new File("SHA1.txt"))) {
    String sha1Txt = s.useDelimiter("\\Z").next();
    ...
    return result;
}



回答2:


If it's being used by another process, I'm guessing some other program has that text file open. Try closing the other program.



来源:https://stackoverflow.com/questions/28905235/java-cannot-delete-file-being-used-by-another-process

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