2

Hi i implemented a java file watcher which reads the file when it is created.

It works fine on development machine. I created a few files and through the logs, the ENTRY_CREATE is called and my program reads the files as expected. The ENTRY_MODIFY is not called.

But on a production machine it behaves differently. Many files are written to the directory, and my program failed to read the files properly when the ENTRY_CREATE is called. I noticed there were a few ENTRY_MODIFY.

How do I tell if the file is completed so my program can read the file properly. From this article, it mentioned that the file is done when the last modified is called. But how do i know? And sometimes ENTRY_MODIFY is not called.

Community
  • 1
  • 1
chrizonline
  • 4,779
  • 17
  • 62
  • 102

1 Answers1

1

I decided to check the file lastmodified. If it stop changing, I continue to process the file. I am monitoring the the logs and if all goes well, I will use this method.

// Check if file is done created by checking change in date modified
    File file = new File("...../filepath");
    long tmpFileLastModified = 0;
    int counter = 0;
    while (true) {
        long fileLastModified = file.lastModified();

        if (fileLastModified != tmpFileLastModified) {
            tmpFileLastModified = fileLastModified;

            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        } else {
            msLogger.debug("fileModifiedCallback: File done modified");
            break;
        }

        counter++;
    }

// do something with the file
chrizonline
  • 4,779
  • 17
  • 62
  • 102