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)); } }