Discuss / Java / 练习参考答案

练习参考答案

Topic source

MayEasLau

#1 Created at ... [Delete] [Delete and Lock User]
	static void listDir(File dir) {
		// : 递归打印所有文件和子文件夹的内容
		File[] fs = dir.listFiles();
		if (fs != null) {
			for (File f : fs) {
				System.out.println(f.getName());
				if(f.isDirectory()) {
					cnt++;
					for(int i=0;i<cnt;i++) {
						System.out.print(" ");
					}
					listDir(f);
					cnt--;
				}
			}
		}
	}

你这 cnt 在哪定义了??

不过 给了 思路 我在想一想

这个 只能 定义 全局变量了。。。。

好像有bug。。。我在看看

改了一天 终于 改完了 

package com.itranswarp.learnjava;

import java.io.File;
import java.io.IOException;

/**
* Learn Java from https://www.liaoxuefeng.com/
*
* @author liaoxuefeng
*/
public class Main {

static int count = 0;

public static void main(String[] args) throws IOException {
// File currentDir = new File("C:\\AAAA");
File currentDir = new File(".");
File canonicalFile = currentDir.getCanonicalFile();
System.out.println(canonicalFile);
listDir(currentDir.getCanonicalFile());
}

static void listDir(File dir) throws IOException {
// TODO: 递归打印所有文件和子文件夹的内容
File[] fs = dir.listFiles();

if (fs != null) {
for (int i = 0; i < fs.length; i++) {

//打印第一条文件或目录
File f = fs[i];

if (count > 0 && f.isFile() && i > 0) {
for (int j = 0; j < count; j++) {
System.out.print(" ");
}
}
System.out.println(f.getName());

//目录
if (f.isDirectory()) {
count++;
if ((f.list().length > 0)) {
for (int j = 0; j < count; j++) {
System.out.print(" ");
}
}
listDir(f);
count--;
}

}
}
}

}


  • 1

Reply