0

Possible Duplicate:
Java: Check if file is already open

I am making a swing utility in which i am creating and using a excel sheet by Apache poi. If the file is already opened while i m trying to access it it throws an exception like some other process is using this excel file. So all i want is to check if that excel file is already opened and if yes then close it.

Community
  • 1
  • 1
wwwcrawl
  • 1
  • 1
  • 1
  • Do you want to close the *other* program or *your* program? – aioobe Jul 18 '12 at 07:52
  • i want to close the excel file – wwwcrawl Jul 18 '12 at 07:53
  • 1
    If another program holds the file open, then you need to either shut down that program or instruct the program to close the file. Which of those two are you after? – aioobe Jul 18 '12 at 07:56
  • by other program it means OS i think. Overall i just opened the target excel by just double click on that and so i got this exception in java that "The process cannot access the file because it is being used by another process" PS my bad its process not program :) – wwwcrawl Jul 18 '12 at 08:00

2 Answers2

2

Did you do some Google search on this topic: Here is some I came up with

I am copying the answer from the first question on stackoverflow here:

File file = new File(fileName);
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
} catch (OverlappingFileLockException e) {
    // File is open by someone else
} finally {
    lock.release();
}

Hope this will be of help.

Community
  • 1
  • 1
Jomoos
  • 12,823
  • 10
  • 55
  • 92
-1

Have you tried this:

File file = new File(pathToFile);
if (file.canRead()) {
  <do whatever you are doing with the file>
}
Stefan Buynov
  • 389
  • 1
  • 7
  • no this is not the solution. this only tells you whether the file can be read or not. it return true in both cases 1. file is open already 2. file is close. – wwwcrawl Jul 18 '12 at 08:06