我有一个外部文本文件,我想绑定到一个标签,这样当外部文件值被修改时,我的UI会自动更新字符串值。
到目前为止,我已经尝试过:
val testid: ObservableStringValue = SimpleStringProperty(File("src/.../test").readText())
在我的边界窗格中,我引用了testid
label.bind(testid)
这会成功读取文件,但编辑测试文件时testid不会自动更新其值。我想尝试使用Handler()强制变量每秒更新一次值,但我相信有一种更聪明的方法来使用属性和属性。observable()将文件和属性绑定在一起。
编辑:
根据mipa关于使用nio2的建议,我很难为计时器生成对象/类:
object DirectoryWatcher {
@JvmStatic fun main(args:Array<String>) {
val watchService = FileSystems.getDefault().newWatchService()
val path = Paths.get(System.getProperty("src/pykotinterface/test"))
path.register(
watchService,
StandardWatchEventKinds.ENTRY_CREATE,
StandardWatchEventKinds.ENTRY_DELETE,
StandardWatchEventKinds.ENTRY_MODIFY)
val key:WatchKey = watchService.take()
while (key != null) {
for (event in key.pollEvents()) {
println(
"Event kind:" + event.kind()
+ ". File affected: " + event.context() + ".")
}
key.reset()
}
}
}
如何调用该对象来运行——它当前位于我的View()类中,TornadFX正在调用该类来生成视图,因此我无法调用DirectWatcher。main()。我是否从其他应用程序类中调用此对象?我很迷路。