[英]monitor a Folder and extract all data in the file using java
我正在尝试监视文件夹/文件的任何更改,然后使用 java 将文件中的所有数据和 append 提取到数据库中。
我已尝试使用 java 中的监视服务 api 来监视文件,如下面的代码片段所示。
import static java.nio.file.StandardWatchEventKinds.*;
import java.io.*;
import java.util.*;
public class FolderMonitor {
public void fileMonitor() throws IOException {
WatchService watchService = FileSystems.getDefault().newWatchService();
Path path = Paths.get("C:/Users/xxxxx/Desktop/yyyyy");
path.register(watchService, ENTRY_CREATE, ENTRY_MODIFY, ENTRY_DELETE);
}
}
非常欢迎任何帮助
所以这就是我实现这一目标的方式,我创建了各种类,如下所示。
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardWatchEventKinds;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
public class FolderMonitor {
public static void fileMonitor() {
final String FOLDER_NAME = "xxxxxxxxxxx";
final String FILE_NAME = "xxxxxx/filename";
try {System.out.println("Watching directory for changes in the info file");
WatchService watchService = FileSystems.getDefault().newWatchService();
Path directory = Paths.get(FOLDER_NAME);
WatchKey watchKey = directory.register(watchService, StandardWatchEventKinds.ENTRY_CREATE,
StandardWatchEventKinds.ENTRY_MODIFY, StandardWatchEventKinds.ENTRY_DELETE);
while (true) {
for (WatchEvent<?> event : watchKey.pollEvents()) {
@SuppressWarnings("unchecked")
WatchEvent<Path> pathEvent = (WatchEvent<Path>) event;
Path fileName = pathEvent.context();
WatchEvent.Kind<?> kind = event.kind();
if (kind == StandardWatchEventKinds.ENTRY_CREATE) {
System.out.println("Info file has been created : " + fileName);
FileReadingToJson.infoFileReading(FILE_NAME);
}
if (kind == StandardWatchEventKinds.ENTRY_DELETE) {
System.out.println("The info file has been deleted: " + fileName);
}
if (kind == StandardWatchEventKinds.ENTRY_MODIFY) {
FileReadingToJson.infoFileReading(FILE_NAME);
}
}
boolean valid = watchKey.reset();
if (!valid) {
break;
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
这就是我读取属性文件并将其解析为 json 的方式
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import org.json.JSONObject;
import org.json.Property;
public class FileReadingToJson {
public static void infoFileReading(String filename) {
try (InputStream input = new FileInputStream(filename)) {
Properties infoFilepropeProperties = new Properties();
infoFilepropeProperties.load(input);
JSONObject jsonObject = Property.toJSONObject(infoFilepropeProperties);
String jsonObjectstring = jsonObject.toString();
System.out.println(jsonObject);
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
目前,这些片段会监控和读取属性文件,并将它们解析为 json 格式。
现在我仍然使用 json 数据在文件发生变化时填充数据库。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.