Skip to content

Instantly share code, notes, and snippets.

@mherman22
Created March 9, 2022 13:29
Show Gist options
  • Save mherman22/8315db6e3667d3e69cb251509db260e4 to your computer and use it in GitHub Desktop.
Save mherman22/8315db6e3667d3e69cb251509db260e4 to your computer and use it in GitHub Desktop.
this class monitors a folder and in particular it monitors the info file. In the infoReading() Method, the data inside the info file is read into a json object whenever the there is a change to the file
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
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;
import java.util.Properties;
import org.json.JSONObject;
import org.json.Property;
public class WatchFolder {
public static void main(String args[]) {
watchFolder();
}
public static void watchFolder() {
final String FOLDER_NAME = "C:/Users/HERMAN MUHEREZA/Documents/Batch057";
final String FILE_NAME = "C:/Users/HERMAN MUHEREZA/Documents/Batch057/info";
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()) {
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);
infoFileReading(FILE_NAME);
}
if (kind == StandardWatchEventKinds.ENTRY_DELETE) {
System.out.println("The info file has been deleted: " + fileName);
}
if (kind == StandardWatchEventKinds.ENTRY_MODIFY) {
infoFileReading(FILE_NAME);
}
}
boolean valid = watchKey.reset();
if (!valid) {
break;
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void infoFileReading(String filename) {
try (InputStream input = new FileInputStream(filename)) {
Properties infoFilepropeProperties = new Properties();
infoFilepropeProperties.load(input);
System.out.println("....changing properties into a json object....");
JSONObject jsonObject = Property.toJSONObject(infoFilepropeProperties);
System.out.println(jsonObject);
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
@mherman22
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment