1

I want to create a program in Java/Spring that listens always a directory. If a particular called for example "example.txt" is created in this directory then the program reads it and do some stuff and then continues listening. If this txt file is not created then nothing happens and it continues listening.

Any idea about how can I create this listener part?

Thank you so much for your help

Ivan Sanchez
  • 79
  • 1
  • 1
  • 6
  • I am not aware of such functionality of Spring and of Java in general. You can read the directory content but there is no way to trigger it to the application that something happened on the system level. You can use a scheduler to periodically check the state of the directory content (files with their modification date) and compare with theri previous state (store in the database). I see no other way to do so. – Nikolas Charalambidis Oct 01 '20 at 09:59
  • @Nikolas I haven't used it myself, but there is `java.nio.file.WatchService`. – Mark Rotteveel Oct 01 '20 at 12:03

1 Answers1

1

You can use the WatchService added in Java 7

WatchService watchService = FileSystems.getDefault().newWatchService();
Path path = Paths.get("example.txt");
WatchKey watchKey = path.register(watchService, StandardWatchEventKinds...);

More information here and here

Guillaume
  • 14,306
  • 3
  • 43
  • 40
  • Hi, how does it work? Does it stop the execution waiting for a change and when we made the change it continues the execution or how? Thanks – Ivan Sanchez Oct 02 '20 at 07:04
  • There are multiple ways to do it, either polling periodically or calling the blocking methods to wait for an event, it is well explained here: https://www.baeldung.com/java-nio2-watchservice – Guillaume Oct 02 '20 at 08:49
  • The problem is that I can't update the java version, I am working with a lower one, so if I use WatchService classes I get errors. Is there other way to monitorize the directory as it happens in WatchService? Thank you so much – Ivan Sanchez Oct 05 '20 at 14:36
  • Your question was marked as a duplicate, if you look at the previous question you'll find some proposals – Guillaume Oct 05 '20 at 14:53