Java Cannot delete file 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 do it, he 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 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?

+1
source share
2 answers

I think the 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 an instance of the scanner, but obviously do not close it. You should do something like this:

 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; } 
+2
source

If it is used by another process, I assume that some other program will open this text file. Try closing another program.

0
source

All Articles