java 文件目录树
1. 目标格式,使用tree命令时,目录树格式如下。
public class TreeTest {
public static void main(String[] args) { File root = new File("${path}/apache-tomcat-7.0.93/webapps/manager/"); tree(root, 0, -1, ""); } public static void tree(File file, int index, int parentIndex, String parentFix) { String nowFix = ""; if (parentIndex == 0) { nowFix = parentFix + " "; } else if(parentIndex > 0) { nowFix = parentFix + "| "; } System.out.println(nowFix + (parentIndex >= 0 ? "|-" : "") + file.name()); if (file.isDirectory()) { files[] files = file.listFiles(); if (files == null) return; List<File> fileList = Arrays.stream(files).sorted((f1, f2) -> f2.getName().compareToIgnoreCase(f1.getName())).collect(Collections.toList()); for (int i = fileList.size() - 1; i >= 0; --i) {
File f = fileList.get(i); tree(f, i, index, nowFix); } } } }
3. 代码输出:
manager
|-images
| |-add.gif
| |-asf-logo.svg
| |-code.gif
| |-design.gif
| |-docs.gif
| |-fix.gif
| |-tomcat.gif
| |-update.gif
| |-void.gif
|-index.jsp
|-META-INF
| |-context.xml
|-status.xsd
|-WEB-INF
| |-jsp
| | |-401.jsp
| | |-403.jsp
| | |-404.jsp
| | |-sessionDetail.jsp
| | |-sessionsList.jsp
| |-web.xml
|-xform.xsl
4. 分析
目录名或文件名显示的格式都是 “|-文件名”,不同的是前缀,而前缀由其父文件的显示前缀和发文件在其兄弟文件排序中的序号决定。