Created
April 24, 2022 17:35
-
-
Save theapache64/823d217ae2e20e7b1ebd991fd01599a1 to your computer and use it in GitHub Desktop.
To watch file changes
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.File | |
import java.nio.file.* | |
class FileWatcher(watchFile: String) { | |
private val folderPath: Path | |
private val watchFile: String | |
init { | |
val filePath = Paths.get(watchFile) | |
val isRegularFile = Files.isRegularFile(filePath) | |
require(isRegularFile) { | |
// Do not allow this to be a folder since we want to watch files | |
"$watchFile is not a regular file" | |
} | |
// This is always a folder | |
folderPath = filePath.parent | |
// Keep this relative to the watched folder | |
this.watchFile = watchFile.replace(folderPath.toString() + File.separator, "") | |
} | |
@Throws(Exception::class) | |
fun watchFile( | |
onModified: () -> Unit, | |
) { | |
// We obtain the file system of the Path | |
val fileSystem = folderPath.fileSystem | |
fileSystem.newWatchService().use { service -> | |
// We watch for modification events | |
folderPath.register(service, StandardWatchEventKinds.ENTRY_MODIFY) | |
// Start the infinite polling loop | |
while (true) { | |
// Wait for the next event | |
val watchKey: WatchKey = service.take() | |
for (watchEvent: WatchEvent<*> in watchKey.pollEvents()) { | |
// Get the type of the event | |
val kind: WatchEvent.Kind<*> = watchEvent.kind() | |
if (kind === StandardWatchEventKinds.ENTRY_MODIFY) { | |
val watchEventPath: Path = watchEvent.context() as Path | |
// Call this if the right file is involved | |
if ((watchEventPath.toString() == watchFile)) { | |
onModified() | |
} | |
} | |
} | |
if (!watchKey.reset()) { | |
// Exit if no longer valid | |
break | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment