java无法删除另一个进程正在使用的文件 [英] java Cannot delete file, being used by another process
问题描述
我有这段代码
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"));
当我执行它时说
java.nio.file.FileSystemException
进程无法访问该文件,因为它正由另一个进程使用(在sun.nio.fs.WindowsException中)
java.nio.file.FileSystemException
The process cannot access the file because it is being used by another process (in sun.nio.fs.WindowsException)
在 sameSha1()
中我有:
String sha1Txt = new Scanner(new File("SHA1.txt")).useDelimiter("\\Z").next();
我想删除文件'SHA1.txt'。我怎么能这样做?
I want to delete the file 'SHA1.txt'. How can I do this?
推荐答案
我想用 sameSha1
你打开 SHA1.txt
阅读它而忘记关闭它。
I guess with sameSha1
you open SHA1.txt
to read it and you forget to close it.
编辑:
在评论中,您在 sameSha1
中包含以下行:
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();
}
或者@HuStmpHrrr在Java 7中建议:
Or as @HuStmpHrrr suggests in Java 7:
try(Scanner s = new Scanner(new File("SHA1.txt"))) {
String sha1Txt = s.useDelimiter("\\Z").next();
...
return result;
}
这篇关于java无法删除另一个进程正在使用的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!