用java构造一个带层次的文件目录遍历器
import java.util.List; import java.io.File; import java.util.ArrayList; public class IteratorUtil { private static int level=0; public static void IteratorDir(File file){ if(file!=null){ if(file.isFile()||file.listFiles().length ==0){ return; }else{ File[] files=file.listFiles(); files=sort(files); for (File f : files) { StringBuilder sb = new StringBuilder(); if(f.isFile()){ sb.append(getTab(level)); sb.append(f.getName()); }else{ sb.append(getTab(level)); sb.append(f.getName()); sb.append("\\"); } System.out.println(sb.toString()); if(f.isDirectory()){ level++; IteratorDir(f); level--; } } } } } private static File[] sort(File[] files){ List<File> flist = new ArrayList<File>(); for (File f : files) { if(f.isDirectory()){ flist.add(f); } } for (File f : files) { if(f.isFile()){ flist.add(f); } } return flist.toArray(new File[flist.size()]); } private static String getTab(int level){ StringBuilder sb = new StringBuilder(); for (int i = 0; i < level; i++) { sb.append("\t"); } return sb.toString(); } }