cancel
Showing results for 
Search instead for 
Did you mean: 

How to check a text file is already opened by another process

Former Member
0 Kudos

Hi All,

We are facing a requirement to check a simple text file that has been already opened by some other process using java programming.We are using simple file reading concepts to read the content of those text file

For eg: Let us take sample.txt in any of the system location which is manually opened and we need to check that sample.txt is opened or not using java programming.

If it is not opened by any process then only we should read that file otherwise we shouldn't.

ANY GUIDANCE WILL BE HELPFUL...

Thanks & Regards,

Rumeshbabu

Accepted Solutions (0)

Answers (1)

Answers (1)

Former Member
0 Kudos

Since the concept of when a file is open differs between different platforms, there is no easy way to build this kind of check in Java. You could make native calls or use locking instead.

Former Member
0 Kudos

Hi Christian,

Thanks. But could you please explain more about using lock concepts.

ANY GUIDANCE WILL BE GREATLY HELPFUL..

Thanks & Regards,

Rumeshbabu.

Former Member
0 Kudos

The general concept is quite simple. Let us assume you have two processes A (the first process) and B (your Java read program). Before A opens the file, A checks if a lock does not yet exists and A creates another empty file called <filename>.lock which serves as our lock. Once A has finished opening that file, it releases the lock (deletes <filename>.lock). Whenever B wants to access the file, it checks if a lock already exists (if <filename>.lock exists, B will not access the file). This is a bit simplified, but should illustrate the concept.

Could you give some more information about your scenario to see if that could be applied here?

Former Member
0 Kudos

Hi Christian,

Thanks. Our scenario is...

1. We have log files(in.txt) which is scheduled everyday for tracking and the scheduler will be writing the file ,it will be closed by night 11.

2.So in case if we write any java code to access that log file(using io file concept in java) we need access to that log file from our standalone java program only after night 11 0 clock.

3.So we should check a condition whether that log file has been already used by some other process.

Thanks & Regards.

Rumeshbabu

Former Member
0 Kudos

In your scenario, you have several options:

a. You could rotate your log after 11 so that you have one log file for everyday until 11.

Then you can just have a java program that waits for the file to be created and access it.

b. If the lines in the log include timestamp, you could read all lines that were written between 11 and 11. Why would you need to know if someone else is opening the file?

c. If the log file is closed every night at 11, why don't you just execute or schedule your java program after 11 pm?

From the given scenario, I do not understand why there is a requirement to check for access by another process?