在zk根目录下有a,zookeeper两个节点,在a下有孩子a1.
[zk: s201:2181(CONNECTED) 9] ls /
[a, zookeeper]
[zk: s201:2181(CONNECTED) 10] ls /a
[a1]
递归代码如下:
@Test
public void TestZKAll() throws Exception {
ls("/");
}
/**
* 列出指定path下所有孩子
*/
public void ls(String path) throws Exception {
System.out.println(path);
ZooKeeper zk = new ZooKeeper("192.168.xxx.xxx:2181",5000,null);
List<String> list = zk.getChildren(path,null);
//判断是否有子节点
if(list.isEmpty() || list == null){
return;
}
for(String s : list){
//判断是否为根目录
if(path.equals("/")){
ls(path + s);
}else {
ls(path +"/" + s);
}
}
}
输出结果:
/a
/a/a1
/zookeeper
/zookeeper/quota
Process finished with exit code 0