


Java uses WatchService to monitor file changes in a directory in real time and parse it line by line. Detailed example
First let’s talk about the requirements: Upload files in the agreed format to the specified directory on the server through ftp. The application can monitor the changes in the files in the directory in real time. If the uploaded file format meets the requirements, it will read and parse each line before writing. Enter the database and rename the file after parsing.
1. The initial idea
Set up a scheduled task to read the file changes in the specified directory every one minute. If there are files that meet the format, Just analyze it.
This method is very cumbersome and inefficient. All efficiency is consumed in traversing, saving states, and comparing states! And you can't take advantage of many features of the OS.
2. Introduction to WatchService
1. The object of this class is the native file system monitor of the operating system! We all know that the OS's own file system monitor can monitor changes in all files on the system. This kind of monitoring does not require traversal or comparison. It is a monitoring based on signal sending and receiving, so the efficiency must be the highest; now Java has After packaging, you can use the OS file system monitor directly in Java programs;
2. Get the file system monitor under the current OS platform:
i. WatchService watcher = FileSystems .getDefault().newWatchService();
ii. From the class name FileSystems, we can see that this must belong to the OS platform file system. Next, we can see that this series of methods can directly obtain a file monitoring Monitor;
There is no need to understand the specific meaning of this string of methods in depth for the time being, just know how to use it first;
3. We all know that multiple monitors can be opened at the same time on the operating system. Therefore, Java programs are no exception. The above code only obtains one monitor. You can also use the same code to obtain multiple monitors at the same time;
4. The monitor is actually a background thread. The signal sent by the background monitoring file changes. The monitor obtained here through the above code is only a newly initialized thread. It has not even entered the ready state, it is just initialized;
3. Implementation process
In fact, it is to create a thread during initialization, and then use watchService to monitor the changes in files in the directory in real time. If a file that meets the conditions is added, the file will be parsed according to the agreed format and then written to the database. Details Proceed as follows!
1. Web.xml listener configuration file monitoring listener
<?xml version="1.0" encoding="UTF-8"?><web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://java.sun.com/xml/ns/javaee "><context-param><param-name>contextConfigLocation</param-name><param-value>classpath:root-context.xml</param-value></context-param><filter><filter-name>CharacterEncodingFilter</filter-name><filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class><init-param><param-name>encoding</param-name><param-value>UTF-8</param-value></init-param><init-param><param-name>forceEncoding</param-name><param-value>true</param-value></init-param></filter><filter-mapping><filter-name>CharacterEncodingFilter</filter-name><url-pattern>/*</url-pattern></filter-mapping><filter><filter-name>sitemesh</filter-name><filter-class>com.opensymphony.sitemesh.webapp.SiteMeshFilter</filter-class></filter><filter-mapping><filter-name>sitemesh</filter-name><url-pattern>/*</url-pattern></filter-mapping><servlet><servlet-name>appServlet</servlet-name><servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class><init-param><param-name>contextConfigLocation</param-name><param-value>classpath:servlet-context.xml</param-value></init-param><load-on-startup>1</load-on-startup></servlet><servlet-mapping><servlet-name>appServlet</servlet-name><url-pattern>/</url-pattern></servlet-mapping><!-- 配置spring监听器 --><listener><listener-class>org.springframework.web.context.ContextLoaderListener</listener-class></listener><!-- 配置监控文件变化监听器 --><listener><listener-class>com.zealer.ad.listener.ThreadStartUpListenser</listener-class></listener><listener><listener-class>com.zealer.ad.listener.SessionLifecycleListener</listener-class></listener> <jsp-config> <taglib> <taglib-uri>/tag</taglib-uri> <taglib-location>/WEB-INF/tag/tag.tld</taglib-location> </taglib></jsp-config><welcome-file-list><welcome-file>index.jsp</welcome-file></welcome-file-list><session-config><session-timeout>45</session-timeout></session-config></web-app>
2. Write a ThreadStartUpListenser class to implement ServletContextListener and create a background thread when tomcat starts
ThreadStartUpListenser.java
package com.zealer.ad.listener;import javax.servlet.ServletContextEvent;import javax.servlet.ServletContextListener;import org.apache.commons.logging.Log;import org.apache.commons.logging.LogFactory;import org.springframework.stereotype.Component;import com.zealer.ad.task.WatchFilePathTask; @Componentpublic class ThreadStartUpListenser implements ServletContextListener {private static WatchFilePathTask r = new WatchFilePathTask();private Log log = LogFactory.getLog(ThreadStartUpListenser.class); /* * tomcat启动的时候创建一个线程 * */@Overridepublic void contextInitialized(ServletContextEvent paramServletContextEvent) { r.start(); log.info("ImportUserFromFileTask is started!"); } /* * tomcat关闭的时候销毁这个线程 * */@Overridepublic void contextDestroyed(ServletContextEvent paramServletContextEvent) { r.interrupt(); } }
3. Create a specified directory file change monitoring class
WatchFilePathTask.java
WatchFilePathTask Log log = LogFactory.getLog(WatchFilePathTask. String filePath = ConfigUtils.getInstance().getValue("userfile_path" watchService ="获取监控服务"+="@@@:Path:"+ String todayFormat = DateTime.now().toString("yyyyMMdd"= = existFiles.listFiles( ((todayFormat+".txt" ( !=ImportUserFromFileTask task = (ImportUserFromFileTask) SpringUtils.getApplicationContext().getBean("importUserFromFileTask"WatchKey key = (= (WatchEvent<?>String fileName =((todayFormat+".txt"= path.toFile().getAbsolutePath()+File.separator+"import filePath:"+ImportUserFromFileTask task = (ImportUserFromFileTask) SpringUtils.getApplicationContext().getBean("importUserFromFileTask");"启动线程导入用户数据"+
4. Create a thread for parsing user files and importing database, started by WatchFilePathTask
package com.zealer.ad.task;import com.zealer.ad.entity.AutoPutUser;import com.zealer.ad.entity.Bmsuser;import com.zealer.ad.service.AutoPutUserService;import org.apache.commons.logging.Log;import org.apache.commons.logging.LogFactory;import org.joda.time.DateTime;import java.io.BufferedReader;import java.io.File;import java.io.FileInputStream;import java.io.InputStreamReader;import java.util.Date;import javax.annotation.Resource;/** * 解析用户文件及入库线程,由WatchFilePathTask启动 * @author cancer * */public class ImportUserFromFileTask extends Thread {private Log log = LogFactory.getLog(ImportUserFromFileTask.class);private String fileName; @Resource(name = "autoPutUserService")private AutoPutUserService autoPutUserService; @Overridepublic void run() { File file = new File(fileName);if (file.exists() && file.isFile()) { log.debug(":@@@准备开始休眠10秒钟:" + file);//休眠十分钟,防止文件过大还没完全拷贝到指定目录下,这里的线程就开始读取文件try { sleep(10000); } catch (InterruptedException e1) { e1.printStackTrace(); } InputStreamReader read;try { read = new InputStreamReader(new FileInputStream(file), "UTF-8"); BufferedReader bufferedReader = new BufferedReader(read); String lineTxt = null;int count = 0; Boolean f = false;while ((lineTxt = bufferedReader.readLine()) != null) {if ((null == lineTxt) || "".equals(lineTxt)) {continue; }if (lineTxt.startsWith("'")) { lineTxt = lineTxt.substring(1, lineTxt.length()); }//解析分隔符为', 'String[] lines = lineTxt.split("', '");int length = lines.length;if (length < 2) {continue; } Bmsuser bmsuser = new Bmsuser(); bmsuser.setName(lines[0]);if (!"".equals(lines[1])) { bmsuser.setCity(lines[1]); } //根据唯一索引已经存在的数据则不插入f = autoPutUserService.insertIgnore(bmsuser);if (f) { count++; } }//汇总数据AutoPutUser autoPutUser = new AutoPutUser(); autoPutUser.setTotalCount(autoPutUserService.getUserCount()); autoPutUser.setCount(count); autoPutUser.setCountDate(new Date(System.currentTimeMillis())); String today = DateTime.now().toString("yyyy-MM-dd"); Integer oldCount = autoPutUserService.getOldCount(today);//如果今天导入过了就更新否则插入if (!oldCount.equals(0)) { autoPutUserService.updateUserData(autoPutUser, today, oldCount); } else { autoPutUserService.gatherUserData(autoPutUser); }//注意:要关闭流 read.close(); } catch (Exception e) { log.error(e.getMessage(), e); } File newFile = new File(file.getPath() +System.currentTimeMillis() + ".complate"); file.renameTo(newFile); } else { log.error(fileName + " file is not exists"); } }public String getFileName() {return fileName; }public void setFileName(String fileName) {this.fileName = fileName; }public AutoPutUserService getAutoPutUserService() {return autoPutUserService; }public void setAutoPutUserService(AutoPutUserService autoPutUserService) {this.autoPutUserService = autoPutUserService; } }
Attached:
1. sql script
CREATE TABLE `bmsuser` ( `id` int(255) unsigned NOT NULL AUTO_INCREMENT, `name` varchar(32) DEFAULT NULL , `city` varchar(32) DEFAULT NULL COMMENT , PRIMARY KEY (`bmsid`), UNIQUE KEY `bbLoginName` (`bbLoginName`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
2. File format, named yyyyMMdd.txt
'张三', '深圳'
The above is the detailed content of Java uses WatchService to monitor file changes in a directory in real time and parse it line by line. Detailed example. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Guide to Perfect Number in Java. Here we discuss the Definition, How to check Perfect number in Java?, examples with code implementation.

Guide to Weka in Java. Here we discuss the Introduction, how to use weka java, the type of platform, and advantages with examples.

Guide to Smith Number in Java. Here we discuss the Definition, How to check smith number in Java? example with code implementation.

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

Guide to TimeStamp to Date in Java. Here we also discuss the introduction and how to convert timestamp to date in java along with examples.

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.
