Memo: [Java] If a file is in the monitored directory, process it.

background

Last time, I wrote Process and output CSV file. I want to process the CSV file when it comes into the target directory. I thought, so I will write down the code.

監視.png

** First, monitor the directory **

-** WatchService usage memo ** -** Wait for the file to be created in Java, detect the creation and then perform the next process ) ** : grinning: I referred to this page. Thank you very much.

test.java


import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
import java.nio.file.Watchable;

import static java.nio.file.StandardWatchEventKinds.*;
import static java.nio.file.WatchEvent.*;

public class test {

    public static void main(String[] args) throws Exception {
        Path dir = Paths.get("C://develop//BOX");
        WatchService watcher = FileSystems.getDefault().newWatchService();
        dir.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);

        for (;;) {
            WatchKey watchKey = watcher.take();
            for (WatchEvent<?> event: watchKey.pollEvents()) {
                if (event.kind() == OVERFLOW) continue;

                WatchEvent<Path> ev = cast(event);
                Path name = ev.context();
                Path child = dir.resolve(name);
                System.out.format("%s: %s\n", event.kind().name(), child);
            }
            watchKey.reset();
        }
    }

    @SuppressWarnings("unchecked")
    static <T> WatchEvent<T> cast(WatchEvent<?> event) {
        return (WatchEvent<T>)event;
    }
}

Now, create a directory called ** BOX ** in ** C: \ develop ** and 1.png

Try compiling test.java anywhere and running the class. (* This time I am running with D: ) 2.png

Wow! If you get an error when compiling:: beginner: ** here ** It will be helpful.

Now let's run the class file. Try putting a suitable file in the BOX directory. 3.png

Oops! The sample .txt that I put in the directory It says ENTRY_CREATE and ENTRY_MODIFY. 4.png

When I delete the file from the directory, I see ENTRY_DELETE. 5.png

I think that you can understand it after actually moving it, so I pasted the image when I moved it first This is written in test.java. (The comment is written in my interpretation, so I may have made a mistake ...) The second line ** WatchService watcher = FileSystems.getDefault (). newWatchService (); ** It seems to be a fixed phrase, so I will use it as it is without thinking deeply.

Path dir = Paths.get("C://develop//BOX");                            //"dir"Specify the directory to be monitored in
WatchService watcher = FileSystems.getDefault().newWatchService();   //WatchService"watcher"Created with the name
dir.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);     //"dir"Specify the event to be monitored in(Create,Delete,Change)
for (;;) {                                                           //Implement an infinite loop to wait for an event
   WatchKey watchKey = watcher.take();                               //Watcher key from watcher"watchKey"To get
   for (WatchEvent<?> event: watchKey.pollEvents()) {                //You can get the List where WatchEvent is stored by pollEvents method.
       if (event.kind() == OVERFLOW) continue;                       //"OVERFLOW"Is a special monitoring event that indicates that the event has disappeared or was destroyed

        WatchEvent<Path> ev = cast(event);
        Path name = ev.context();                                    //"name"Get in event context and set the file name
        Path child = dir.resolve(name);                              //Full path with resolve method("dir"In the path of"name"Added)The set
        System.out.format("%s: %s\n", event.kind().name(), child);   //At the time of output, [event name:Instructions to output with [Full path of file]
   }
   watchKey.reset();                                                 //Reset the watch key(To return the WatchKey state to READY)

** Combine the processing to process csv **

Previous code [Process (extract, change) the read csv and output]

test.java


import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class test{

    public static void main(String[] args) {
        process("20180712.csv",  ":00,","output.csv");
    }

    public static void process(String read_file, String searchString, String output_file){

        try(FileReader fr = new FileReader(read_file);BufferedReader br = new BufferedReader(fr);
            FileWriter fw = new FileWriter(output_file);BufferedWriter bw = new BufferedWriter(fw)){

            String line;
            while ((line = br.readLine()) != null) {
                Pattern p = Pattern.compile(searchString);
                Matcher m = p.matcher(line);
                if (m.find()){
                    String[] csvArray;
                    csvArray = line.split(",");
                    String time  = csvArray[0];
                    float press = Float.parseFloat(csvArray[1])%10000;
                    String pressure = String.format("%.2f", press);
                    String temperature  = csvArray[2];
                    String outputLine = String.join(",",time,pressure,temperature);
                    bw.write(outputLine);
                    bw.newLine();
                }else{ 
                }
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}

The previous code and the code I wrote above haven't changed much. It's almost just combined.

test.java


import java.nio.file.FileSystems;      //Required for directory monitoring
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
import java.nio.file.Watchable;
import static java.nio.file.StandardWatchEventKinds.*;
import static java.nio.file.WatchEvent.*;

import java.io.BufferedReader;        //Required to process and output csv
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class test {

    public static void main(String[] args) throws Exception {
        
        Path dir = Paths.get(System.getenv("CSV_DIR"));       //This time, the directory to be monitored is an environment variable"CSV_DIR"Set to
        WatchService watcher = FileSystems.getDefault().newWatchService();
        dir.register(watcher, ENTRY_CREATE);                  //This time ENTRY_OK if only CREATE is detected
   
        for (;;) {
            WatchKey watchKey = watcher.take();
            for (WatchEvent<?> event: watchKey.pollEvents()) {
                if (event.kind() == OVERFLOW) continue;              
                WatchEvent<Path> ev = cast(event);
                Path name = ev.context();
                Path child = dir.resolve(name);
                String newfile =String.format("%s", child);

                process(newfile, ":00,","D://tedkuma//★"+name); //Pass the full path of the detected file to the file read by process
                System.out.println("Output success:"+name);
            }
            watchKey.reset();
        }  
    }

    @SuppressWarnings("unchecked")
    static <T> WatchEvent<T> cast(WatchEvent<?> event) {
        return (WatchEvent<T>)event;
    }

    public static void process(String read_file, String searchString, String output_file){ //The following is the same as the previous one

        try(FileReader fr = new FileReader(read_file);BufferedReader br = new BufferedReader(fr);
            FileWriter fw = new FileWriter(output_file);BufferedWriter bw = new BufferedWriter(fw)){

            String line;
            while ((line = br.readLine()) != null) {
                Pattern p = Pattern.compile(searchString);
                Matcher m = p.matcher(line);
                if (m.find()){
                    String[] csvArray;
                    csvArray = line.split(",");
                    String time  = csvArray[0];
                    float press = Float.parseFloat(csvArray[1])%10000;
                    String pressure = String.format("%.2f", press);
                    String temperature  = csvArray[2];
                    String outputLine = String.join(",",time,pressure,temperature);
                    bw.write(outputLine);
                    bw.newLine();
                }else{ 
                }
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}

Since Japanese comments and ★ marks are included in the java file javac alone will result in a compile error: sweat: : skull: Error: This character cannot be mapped to encoding MS932, so it will appear. This time I'm compiling with ** javac -encodhing utf-8 test.java **. Let's run it. 11.png

I set the environment variable "CSV_DIR" to the location C: \ develop \ monitored. (This monitored directory) Put the CSV file you want to process in this. 12.png

The file name put in the directory is displayed after Output success :. 13.png

Check the tedkuma directory of the D drive specified as the output destination. A file with a star at the beginning of the file name is output, and the csv inside is also processed. 14.png

This time is over.

Recommended Posts

Memo: [Java] If a file is in the monitored directory, process it.
Java11: Run Java code in a single file as is
How to save a file with the specified extension under the directory specified in Java to the list
Unzip the zip file in Java
Get the public URL of a private Flickr file in Java
Isn't it reflected even if the content is updated in Rails?
Determining if a custom keyboard is enabled in Android Studio (Java)
What is a class in Java language (3 /?)
Memo: [Java] Check the contents of the directory
Organized memo in the head (Java --Array)
What is the best file reading (Java)
What is a class in Java language (1 /?)
What is a class in Java language (2 /?)
What is the main method in Java?
[Java8] Search the directory and get the file
The story of forgetting to close a file in Java and failing
Sample program that returns the hash value of a file in Java
How to get the absolute path of a directory running in Java
Even though the property file path is specified in the -cp option, it is not recognized as a classpath.
If it is Ruby, it is efficient to make it a method and stock the processing.
Read a string in a PDF file with Java
A story about the JDK in the Java 11 era
Organized memo in the head (Java --Control syntax)
Java: Download the file and save it in the location selected in the dialog [Use HttpClient]
If the parameter is an array, how to include it in Stopara's params.permit
The ruby version is managed in the .rbenv / version file
The intersection type introduced in Java 10 is amazing (?)
Measure the size of a folder in Java
Organized memo in the head (Java --instance edition)
A troublesome story when deleting the gems file created in the gem development directory.
A bat file that uses Java in windows
How to ZIP a JAVA CSV file and manage it in a Byte array
[Java] Read the file in src / main / resources
[Java] Is it unnecessary to check "identity" in the implementation of the equals () method?
Organized memo in the head (Java --Data type)
I can't remember the text file input / output in Java, so I summarized it.
[Java] Something is displayed as "-0.0" in the output
[Java] When putting a character string in the case of a switch statement, it is necessary to make it a constant expression
Even if I want to convert the contents of a data object to JSON in Java, there is a circular reference ...
[Java] Integer information of characters in a text file acquired by the read () method
The end of catastrophic programming # 03 "Comparison of integers, if" a> b ", assume that it is" a --b> 0 ""
Access the war file in the root directory of Tomcat
Which is better, Kotlin or Java in the future?
Write a class in Kotlin and call it in Java
Is it faster if the docker bind mount is readonly?
[Personal memo] Make a simple deep copy in Java
A note for Initializing Fields in the Java tutorial
[Java] Get the file in the jar regardless of the environment
[Java] Get the file path in the folder with List
Output true with if (a == 1 && a == 2 && a == 3) in Java (Invisible Identifier)
Program to determine if it is a leap year
How to convert a file to a byte array in Java
21 Load the script from a file and execute it
The story that .java is also built in Unity 2018
How to perform a specific process when the back button is pressed in Android Fragment
If you want to make a Java application a Docker image, it is convenient to use jib.
When a Java file created with the Atom editor is garbled when executed at the command prompt
Even if I write the setting of STRICT_QUOTE_ESCAPING in CATALINA_OPTS in tomcat8.5, it is not reflected.
Solution if you delete the migration file in the up state
Directory is not created even if directory task is described in Rakefile
It doesn't work if the Map key is an array