kafka内部全部的实现都是经过TopicCommand的main方法,经过java代码调用API,TopicCommand.main(options)的方式只能打印到控制台,不能转换到一个list。java
下面讲解下如何转换为list:spa
一、查看主题(Topic)code
【命令方式】:bin/kafka-topics.sh --list --zookeeper 192.168.2.212:2181/kafkablog
【JAVA API方式】:get
public static void main(String[] args) {
String[] options = new String[]{ "--list", "--zookeeper", "192.168.2.212:2181/kafka" ByteArrayOutputStream byteStream = new ByteArrayOutputStream(1024*3); // cache stream PrintStream cacheStream = new PrintStream(byteStream); // old stream PrintStream oldStream = System.out; System.setOut(cacheStream); TopicCommand.main(options); String message = byteStream.toString(); List<String> ls = new ArrayList<String>(); String[]ss = message.split("\n"); ls = Arrays.asList(ss); // Restore old stream System.setOut(oldStream); for(int i=0;i<ss.length;i++){//循环遍历转换后的list中的topic System.out.println(ls.get(i)); } }