dtonhofer

dtonhofer

Functional Programming in Java, Second Edition: p.65 "WatchFileChange.java"

Suggesting a text change:

We read:

We’ve registered a WatchService to observe any change to the current directory.

but what actually happens is

We’ve registered a path with a filesystem WatchService to get told about ‘modification’ changes to the current directory.

On my system, file deletion does not give rise to a notification, but creation does (probably because after creation, the file is additionally modified)

The text

"Report any file changed within next 1 minute..."

should really say

System.out.println("Report the first change on '" + path + "' within the next 1 minute...");

Note that the code given uses an inner loop. At this point, I really feel we should use collect():

if(watchKey != null) {
   watchKey.pollEvents()
      .stream()
      .forEach(event ->
         System.out.println(event.context()));
}

Nicer:

String res = (watchKey == null) ? "nothing happened at all!" :
                        watchKey.pollEvents()
                                .stream()
                                .map(event -> event.context().toString())
                                .collect(Collectors.joining(", "));

As I had some trouble understanding how the WatchService actually works and what those keys are doing, here is the full method

    public void watchFileChange() throws IOException {
        final Path path = Paths.get(theDir);
        String res;
        // Try-with-resources to close the WatchService at the end
        // (and thus cancel all the WatchKeys registered with it)
        try (WatchService watchService = path.getFileSystem().newWatchService()) {
            try {
                // No need to retain the WatchKey returned by path.register()
                path.register(watchService, StandardWatchEventKinds.ENTRY_MODIFY);
                System.out.println("Report the first change on '" + path + "' within the next 1 minute...");
                WatchKey watchKey = null;
                // poll() "Retrieves and removes the next watch key, waiting if necessary up to
                // the specified wait time if none are yet present."
                try {
                    watchKey = watchService.poll(1, TimeUnit.MINUTES);
                } catch (InterruptedException ex) {
                    System.out.println("Got interrupted");
                }
                res = (watchKey == null) ? "nothing happened at all!" :
                        watchKey.pollEvents()
                                .stream()
                                .map(event -> event.context().toString())
                                .collect(Collectors.joining(", "));
            } catch (NoSuchFileException ex) {
                res = "Looks like there is no filesystem entry '" + path + "'";
            }
        }
        System.out.println(res);
    }

Popular Prag Prog topics Top

yulkin
your book suggests to use Image.toByteData() to convert image to bytes, however I get the following error: "the getter ‘toByteData’ isn’t...
New
jamis
The following is cross-posted from the original Ray Tracer Challenge forum, from a post by garfieldnate. I’m cross-posting it so that the...
New
sdmoralesma
Title: Web Development with Clojure, Third Edition - migrations/create not working: p159 When I execute the command: user=> (create-...
New
Mmm
Hi, build fails on: bracket-lib = “~0.8.1” when running on Mac Mini M1 Rust version 1.5.0: Compiling winit v0.22.2 error[E0308]: mi...
New
patoncrispy
I’m new to Rust and am using this book to learn more as well as to feed my interest in game dev. I’ve just finished the flappy dragon exa...
New
adamwoolhether
Is there any place where we can discuss the solutions to some of the exercises? I can figure most of them out, but am having trouble with...
New
rainforest
Hi, I’ve got a question about the implementation of PubSub when using a Phoenix.Socket.Transport behaviour rather than channels. Before ...
New
a.zampa
@mfazio23 I’m following the indications of the book and arriver ad chapter 10, but the app cannot be compiled due to an error in the Bas...
New
mcpierce
@mfazio23 I’ve applied the changes from Chapter 5 of the book and everything builds correctly and runs. But, when I try to start a game,...
New
SlowburnAZ
Getting an error when installing the dependencies at the start of this chapter: could not compile dependency :exla, "mix compile" failed...
New

Other popular topics Top

AstonJ
Or looking forward to? :nerd_face:
New
siddhant3030
I’m thinking of buying a monitor that I can rotate to use as a vertical monitor? Also, I want to know if someone is using it for program...
New
DevotionGeo
I know that -t flag is used along with -i flag for getting an interactive shell. But I cannot digest what the man page for docker run com...
New
AstonJ
You might be thinking we should just ask who’s not using VSCode :joy: however there are some new additions in the space that might give V...
New
Rainer
My first contact with Erlang was about 2 years ago when I used RabbitMQ, which is written in Erlang, for my job. This made me curious and...
New
AstonJ
Continuing the discussion from Thinking about learning Crystal, let’s discuss - I was wondering which languages don’t GC - maybe we can c...
New
New
AstonJ
If you get Can't find emacs in your PATH when trying to install Doom Emacs on your Mac you… just… need to install Emacs first! :lol: bre...
New
PragmaticBookshelf
Author Spotlight: Sophie DeBenedetto @SophieDeBenedetto The days of the traditional request-response web application are long gone, b...
New
PragmaticBookshelf
A Ruby-Centric Chat with Noel Rappin @noelrappin Once you start noodling around with Ruby you quickly figure out, as Noel Rappi...
New

Latest in PragProg

View all threads ❯