3

I was wondering if there is a way to monitor the file system in Java.

Suppose the following

C:\Users\foobar\Desktop\notes.txt

I'd like to monitor which Java process accesses this file and when. The end goal is to return the Class and if possible the method.

Pseudocode example showing what I want to do

public/private class FileReader {
  private void getFileContents(String fileName) throws Exception {
  ...
    FileReader fileReader = Znew FileReader(fileName);

    BufferedReader bufferedReader = new BufferedReader(fileReader);

    while((line = bufferedReader.readLine()) != null) {
      System.out.println(line);
    }
 ...   
}

Separate unrelated Class

public class Monitor {
  ...thread...
  onFileAccessed() {
    System.out.println(processID);
    System.out.println(jarName);
    System.out.println(className);
    System.out.println(methodName);
  }
  ...thread...
}

tyia!

rve
  • 5,897
  • 3
  • 40
  • 64
user316114
  • 803
  • 7
  • 18
  • 1
    Have you had a look at [Watching a Directory for Changes](https://docs.oracle.com/javase/tutorial/essential/io/notification.html) – MadProgrammer Mar 03 '16 at 02:22
  • http://stackoverflow.com/questions/23452527/watching-a-directory-for-changes-in-java – SomeDude Mar 03 '16 at 02:35
  • I would write a wrapper around the WatchService. – Benoit Vanalderweireldt Mar 03 '16 at 03:34
  • This has nothing to do with watching a directory for changes. He wants to know which method of which java process accesses the file. Does jconsole does what you need? Or can you modify the java applications or enable JMX? If not then you can ask the OS which process accesses the file but it wont give you the method. – rve Mar 03 '16 at 07:18
  • Isn't it better to monitor such a stuff on OS level? E.g. lsof on linux or similar for Windows? – JiriS Mar 03 '16 at 07:39
  • Are you running on Solaris, MacOS, or any other OS with a fully-functional and stable dtrace implementation? If so, dump the user-space stack of the process that touched your file and parse the output. – Andrew Henle Mar 03 '16 at 11:31

0 Answers0