0

I have a file say text.csv from which my java programs tries to read/write.

Is there a way in Java to detect if this file is opened for writing when the file has been opened by some user by "double clicking"? If so , how? I'm looking for this kind of code:

if(isOpenForWrite(File file){
//say text.csv is already opened ...
}

Any helpful documentation or other resources is welcome.

KNU
  • 2,560
  • 5
  • 26
  • 39

3 Answers3

0

Best way to check this is checking if you can rename the file

String fileName = "C:\\Text.xlsx";
File file = new File(fileName);

// try to rename the file with the same name
File sameFileName = new File(fileName);

if(file.renameTo(sameFileName)){
    // if the file is renamed
    System.out.println("file is closed");    
}else{
    // if the file didnt accept the renaming operation
    System.out.println("file is opened");
}

or use Apache Common IO library

crzbt
  • 183
  • 4
  • 14
0

I would use the FileChannel.lock to do this.

try { // Get a file channel for the file 
    File file = new File("text.csv");
    FileChannel channel = new RandomAccessFile(file, "rw").getChannel();

    // Blocks until it can retrieve the lock. 
    FileLock lock = channel.lock(); 
    // Try acquiring the lock without blocking. 
    // lock is null or exception if the file is already locked. 

    try { 
        lock = channel.tryLock();
    } catch (OverlappingFileLockException e){}


    lock.release(); // Close the file 
    channel.close();
} catch (Exception e) { 
} 
TA Nguyen
  • 453
  • 1
  • 3
  • 8
0

Source : Java: Check if file is already open

Use this i found this in above commanded link

    boolean isFileUnlocked = false;
    try {
     org.apache.commons.io.FileUtils.touch(yourFile);
    isFileUnlocked = true;
    } catch (IOException e) {
    isFileUnlocked = false;
    }

    if(isFileUnlocked){
    // Do stuff you need to do with a file that is NOT locked.
    } else {
    // Do stuff you need to do with a file that IS locked
    } 
Community
  • 1
  • 1
saravanakumar
  • 1,747
  • 4
  • 20
  • 38