java Cannot delete file, being used by another process

前端 未结 2 395
再見小時候
再見小時候 2020-12-21 09:16

I have this code

 import org.apache.commons.io.FileUtils;
    try {
        FileUtils.copyURLToFile(new URL(SHA1_LINK), new File(\"SHA1.txt\"));
        if(!         


        
相关标签:
2条回答
  • 2020-12-21 09:40

    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;
    }
    
    0 讨论(0)
  • 2020-12-21 09:40

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

    0 讨论(0)
提交回复
热议问题