Is there a way to monitor files using java in Linux ?
I don't mean modifying files, but any reading operations.
For example if I have a file x.txt can I know if the user printed, emailed, or copied data from this file?
If I can't do that in java, is it doable in other languages? Or is there open source program that can do this thing?

- 135
- 2
- 9
-
Would you please guide me by posting a link or keywords, so I can start searching (: – Dalia Sep 22 '14 at 00:02
-
@Dareen This may be obvious, but couldn't you start searching with "Java file monitoring"? That seems fairly straightforward. – Adam Lear Sep 22 '14 at 04:43
-
I'm a bit disappointed this was marked as a duplicate. The question is asking about detecting file reads, not changes. The linked question does not deal with detecting that. – vgel Sep 22 '14 at 22:24
-
@Rotten194 the post was edited to clarify that subtlety only after it was closed. – Matt Ball Dec 04 '14 at 13:58
1 Answers
The Linux inotify API can emit an IN_ACCESS
event for a watched file. Unfortunately, for some reason (Windows compatibility?), the default Java APIs don't expose this.
The third-party library https://bitbucket.org/nbargnesi/inotify-java loads a C++ .so
lib that hooks into the native libraries to get around this. I haven't used the library personally, but reading around the test files a basic approach seems to be:
InotifyContext ic = new InotifyContext();
Random random = new Random(); // for generating file descriptors
ic.addPath("file/you/want/to/monitor", random.nextInt());
final InotifyEventListener i = new InotifyEventListener() {
@Override
public void filesystemEventOccurred(InotifyEvent e) {
if (e.isAccess())
// handle file being accessed
}
};
ic.addListener(i, random.nextInt());
Note: This catches any read from a file, e.g. your own program (I think, you'd need to test that), the user simply opening the file in a text editor and immediately closing it without doing anything, some filesystem crawler automatically finding the file and scanning it for viruses (although Linux, so...). You'll probably want to do some additional checking on the event before immediately yelling at the user or whatever.

- 3,225
- 1
- 21
- 35