#鸿蒙学习大百科#如何创建Watcher对象,用来监听文件或目录变动?

如何创建Watcher对象,用来监听文件或目录变动?

HarmonyOS
2024-10-17 09:16:00
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
懂事的小马
import { common } from '@kit.AbilityKit';
import fs from '@ohos.file.fs';
import { WatchEvent } from '@kit.CoreFileKit';

@Entry
@Component
struct Index {
  private context = getContext(this) as common.UIAbilityContext;

  build() {
    Row() {
      Column() {
        Text("Hello")
          .fontSize(50)
          .fontWeight(FontWeight.Bold)
          .onClick(() => {
            let applicationContext = this.context.getApplicationContext();
            let cacheDir = applicationContext.cacheDir;
            fs.open(cacheDir + "/test.txt", fs.OpenMode.READ_WRITE).then((f: fs.File) => {
              let watcher  =  fs.createWatcher(f.path, 0x2 | 0x10, (watchEvent: WatchEvent) => {
                if (watchEvent.event == 0x2) {
                  console.info(watchEvent.fileName + 'was modified');
                } else if (watchEvent.event == 0x10) {
                  console.info(watchEvent.fileName + 'was closed');
                }
              })
              watcher.start();
              fs.writeSync(f.fd, 'test');
              fs.closeSync(f);
              watcher.stop();
            })
          })
      }
      .width('100%')
    }
    .height('100%')
  }
}
分享
微博
QQ
微信
回复
2024-10-17 14:44:26
相关问题