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
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'。我该怎么做?

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

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

编辑:

根据您的评论,您在 sameSha1 中包含以下行:

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

所以您创建了一个扫描器实例,但没有明确关闭它。你应该这样做:

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

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

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

尝试在使用时auto-close文件资源,像这样:

Path tempFilePath = fileUtil.createTempFile( uploadedInputStream, fileDetail.getFileName() );
File tempFile = tempFilePath.toFile();

try (InputStream is = new FileInputStream( tempFile )) {
    uploadDocument( fileTypeId, description, is );
} catch (IOException e) {
    LOGGER.debug( e );
}

Files.deleteIfExists( tempFilePath );