Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
999 views
in Technique[技术] by (71.8m points)

java Cannot delete file, being used by another process

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...