Search code examples
javashellwatchservice

Run shell inside watch service in java


I want to run shell script inside watch service class to run the shell after new file add to folder. Watch service is working perfectly but when I want to add Runtime.getRuntime().exec("home/user/test.sh"); I recived error. I just add Runtime after this:

   // Dequeueing events
                    Kind<?> kind = null;
                    for(WatchEvent<?> watchEvent : key.pollEvents()) {
                        // Get the type of the event
                        kind = watchEvent.kind();
                        if (OVERFLOW == kind) {
                            continue; //loop
                        } else if (ENTRY_CREATE == kind) {
                            // A new Path was created 
                    Path newPath = ((WatchEvent<Path>) watchEvent).context();
                            // Output
                            System.out.println("New path created: " + newPath);
                          Runtime.getRuntime().exec("home/user/test.sh")

What I have to do?


Solution

  • I thing problems with running script have nothing to do with WatchService, since you don't post actual exception that is throws (that would help a lot) I can only guess what is wrong, so please check this:

    1. Script doesn't have permission to execute (easily fixable by chmod +x path/to/script.sh) - in that case you would get IOException with message like Permission denied or similar

    2. System cannot find your script, since you are using relative path (no / at the beginning of script name) in that case ether use full script name e.g. /home/user/foo/script.sh or use proper relative path ../foo/script.sh - you should check if script exists before running it via exec (How do I check if a file exists in Java?)

    3. Beware that script may be called with working directory of running Java program - so you should pass newly created file path as parameter to script to make it independent of its location

    I followed tutorial that you were using with code:

    if (OVERFLOW == kind) {
                            continue; //loop
                        } else if (ENTRY_CREATE == kind) {
                            // A new Path was created
                            Path newPath = ((WatchEvent<Path>) watchEvent).context();
                            // Output
                            System.out.println("New path created: " + newPath);
                            Runtime.getRuntime().exec(new String[] { "/home/xxx/foo.sh", newPath.toString() });
                        }
    

    and script:

    #!/bin/bash
    echo "FILE CREATED: $1" >> /home/xxx/watch_dir.log
    

    and it worked without any errors.