WatchService中的context如何转化为Path

aa663325 2017-04-22 06:20:47
public class WatchServiceTest
{
public static void main(String[] args)
throws Exception
{
// 获取文件系统的WatchService对象
WatchService watchService = FileSystems.getDefault()
.newWatchService();
FileInputStreamTest averageFigure = new FileInputStreamTest();
// 为C:盘根路径注册监听
Paths.get("F:/3DMGAME/y").register(watchService
, StandardWatchEventKinds.ENTRY_CREATE
, StandardWatchEventKinds.ENTRY_MODIFY
, StandardWatchEventKinds.ENTRY_DELETE);
while(true)
{
// 获取下一个文件改动事件
WatchKey key = watchService.take(); //①
for (WatchEvent<?> event : key.pollEvents())
{
System.out.println(event.context);
}
// 重设WatchKey
boolean valid = key.reset();
// 如果重设失败,退出监听
if (!valid)
{
break;
}
}
}
}


我想监控文件夹里的文件变化(主要就是能监控到文件的增加),然后读取增加的文件。通过WatchService实现了监控功能,
event.context就是增加的文件名。但是RandomAccessFile无法直接读取event.context。
RandomAccessFile fis = new RandomAccessFile(event.context,"r");是错误的。
我想问一下如何把event.context转化为String或者Path。或者有其他的方法?
...全文
166 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
aa663325 2017-04-23
  • 打赏
  • 举报
回复
有谁知道吗?
aa663325 2017-04-22
  • 打赏
  • 举报
回复

public class WatchServiceTest
{
public static void main(String[] args)
throws Exception
{
// 获取文件系统的WatchService对象
WatchService watchService = FileSystems.getDefault()
.newWatchService();
FileInputStreamTest averageFigure = new FileInputStreamTest();
// 为C:盘根路径注册监听
Paths.get("F:/3DMGAME/y").register(watchService
, StandardWatchEventKinds.ENTRY_CREATE
, StandardWatchEventKinds.ENTRY_MODIFY
, StandardWatchEventKinds.ENTRY_DELETE);
while(true)
{
// 获取下一个文件改动事件
WatchKey key = watchService.take();    //①
for (WatchEvent<?> event : key.pollEvents())
{
System.out.println(event.context);
}
// 重设WatchKey
boolean valid = key.reset();
// 如果重设失败,退出监听
if (!valid)
{
break;
}
}
}

62,628

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧