FileInputStream check if a file is in use

mybluegrass
mybluegrass used Ask the Experts™
on
I tried to open a file that's being downloaded using FileInputStream. But it gives me the following errors:
java.io.FileNotFoundException: C:\\tmp\jre-7-ea-bin-b93-windows-i586-13_may_2010.jar (The process cannot access the file because it is being used by another process)
      at java.io.FileInputStream.open(Native Method)
      at java.io.FileInputStream.<init>(FileInputStream.java:137)
      at java.io.FileInputStream.<init>(FileInputStream.java:96)
      ...

I did try to use File file = new File(NewFile);
and put if (file.canRead()) before I use the FileInputStream. But teh canRead( ) returns true while the FileInputStream failed with above exception.

How can I check if the FileInputStream will work?

Thanks!
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Top Expert 2016

Commented:
Try canWrite instead
Mick BarryJava Developer
Top Expert 2010

Commented:
you can't. the file is being used to by another process. While that is occurring you cannot access it.

Author

Commented:
I did try canWrite but the same error occurs. How can I check if the file is in use by another process? And what is the name of the process?
Thanks!
Exploring ASP.NET Core: Fundamentals

Learn to build web apps and services, IoT apps, and mobile backends by covering the fundamentals of ASP.NET Core and  exploring the core foundations for app libraries.

Mick BarryJava Developer
Top Expert 2010

Commented:
canWrite() will give the same error. there is no way to know if its being used by another account that I'm aware of (other than catching the exception)
when different processes access the file, i think you can use
FileChannel.lock()/FileChannel.tryLock(),
this will obtain a exclusive lock on the File for the JVM process, so other process (download) cannot access it and the other way around.





Top Expert 2016

Commented:
>>I did try canWrite but the same error occurs.

Try what mukundha suggests then: IF you can get a lock, you can be pretty sure it's not in use

Author

Commented:
But how can I get the channel? When I used
FileChannel channel = new FileInputStream(NewFile).getChannel();

it will throw exception as described above.

Thanks!
did you try using RandomAccessFile??
Top Expert 2016

Commented:
You don't need to worry about exceptions. Just call tryLock in a loop
Top Expert 2016
Commented:
Top Expert 2016

Commented:
:-)

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial