- public class FileList {
- private static int num;//定义往下循环了多少层
- public static void deepList(File file){
- if (file.isFile() || file.listFiles().length==0) {
- return;
- }
- else {
- File[] files = file.listFiles();
- files = sorted(files);
- for(File f : files){
- StringBuffer buffer = new StringBuffer();
- if (f.isFile()) {
- buffer.append(getTab(num));
- buffer.append(f.getName());
- }else {
- buffer.append(getTab(num));
- buffer.append(f.getName()+"\\");
- }
- System.out.println(buffer.toString());
- if (f.isDirectory()) {
- num++;
- deepList(f);
- num--;
- }
- }
- }
- }
- //对文件夹中的文件进行排序,文件夹在前、文件在后
- public static File[] sorted(File[] files){
- ArrayList<File> sorted = new ArrayList<File>();
- for (File file : files) {
- if (file.isFile()) {
- sorted.add(file);
- }
- if (file.isDirectory()) {
- sorted.add(file);
- }
- }
- return sorted.toArray(new File[files.length]);
- }
- //在每个文件后加上tab
- public static String getTab(int num){
- StringBuffer buffer = new StringBuffer();
- for (int i = 0; i < num; i++) {
- buffer.append("\t");
- }
- return buffer.toString();
- }
- public static void main(String[] args) throws IOException {
- deepList(new File(""));
- }
- }
转载于:https://blog.51cto.com/mazongfei/1111728