- How to check if a file / folder is open before i try to delete it.
Am deleting it programmatically.. before deleting, need to check whether its opened or not
I want something like this,
if(file/folder is open){ //do not delete it }else{ //delete it }
I tried the below set of two codes, but nothing is working
File scrptFile=new File(dirFile); boolean isFileUnlocked = false; try { org.apache.commons.io.FileUtils.touch(scrptFile); isFileUnlocked = true; } catch (IOException e) { isFileUnlocked = false; } if(isFileUnlocked){ // Do stuff you need to do with a file that is NOT locked. System.out.println("file is not locked"); } else { // Do stuff you need to do with a file that IS locked System.out.println("file is locked"); } File file = new File(dirFile); FileChannel channel = new RandomAccessFile(file, "rw").getChannel(); // Get an exclusive lock on the whole file FileLock lock = channel.lock(); try { lock = channel.tryLock(); // Ok. You get the lock System.out.println("Ok. You get the lock"); } catch (OverlappingFileLockException e) { // File is open by someone else System.out.println("File is open by someone else"); } finally { lock.release(); }
Asked
Active
Viewed 1,314 times
0

user2941293
- 21
- 4
-
5Interesting idea, but given the fact that a file lock is OS dependent (and under some OS with multiple different approaches) it might be difficult to ascertain in a clean way. The best way is to try. File#delete returns false if it couldn't delete the file for some reason – MadProgrammer Nov 05 '13 at 07:40
-
1Can u check http://stackoverflow.com/questions/9341505/how-to-check-if-a-file-is-open-by-another-process-java-linux and http://stackoverflow.com/questions/15352010/check-if-a-file-is-open-before-reading-it – Karthik Nov 05 '13 at 07:40
1 Answers
0
You can make use of Apache commons io api,
boolean flagFileNotInUse = false;
try {
org.apache.commons.io.FileUtils.touch(yourFile);
flagFileNotInUse = true;
} catch (IOException e) {
flagFileNotInUse = false;
}
// Then check value of flagFileNotInUse ,
flagFileNotInUse = true, means file not in use
flagFileNotInUse = false, means file in use

Dark Knight
- 8,218
- 4
- 39
- 58
-
Wouldn't it be more clear if you either name the bool flagFileNotInUse or swap the values of the flag? – RFerwerda Nov 05 '13 at 07:48
-
-