java java无法删除文件,正在被另一个进程使用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28905235/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 14:23:54  来源:igfitidea点击:

java Cannot delete file, being used by another process

javadelete-file

提问by alexandre1985

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)

java.nio.file.FileSystemException
进程无法访问该文件,因为它正被另一个进程使用(在 sun.nio.fs.WindowsException 中)

In the sameSha1()I have this:

sameSha1()我有这个:

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

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

我想删除文件“SHA1.txt”。我怎样才能做到这一点?

采纳答案by JuniorCompressor

I guess with sameSha1you open SHA1.txtto read it and you forget to close it.

我猜sameSha1你打开SHA1.txt阅读它而忘记关闭它。

EDIT:

编辑:

From your comment you contain the following line in sameSha1:

从您的评论中,您包含以下行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:

或者正如@HuStmpHrrr 在 Java 7 中所建议的那样:

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

回答by Eric S.

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

如果它被另一个进程使用,我猜其他程序打开了那个文本文件。尝试关闭其他程序。