TA的每日心情 | 开心 2021-3-12 23:18 |
---|
签到天数: 2 天 [LV.1]初来乍到
|
- import java.io.File;
- import java.io.IOException;
- import java.util.Stack;
- import java.util.Queue;
- import java.util.LinkedList;
- public class ListFile{
- public static void main(String[] args) throws IOException {
- File file = new File("c:/java/guest");
- DFS1(file);
- System.out.println("-------------------------------------------------------");
- System.out.println("-------------------------------------------------------");
- // DFS2(file);
- BFS(file);
- }
- // 文件深度非递归遍历
- private static void DFS1(File file) throws IOException {
- Stack< File> stack = new Stack< File>();
- stack.push(file);
- File fileInStack = null;
- while (!stack.isEmpty()) {
- fileInStack = stack.pop();
- System.out.println("dir:" + fileInStack.getCanonicalPath());
- File[] files = fileInStack.listFiles();
- for (File eachFile : files) {
- if (eachFile.isFile()) {
- System.out.println("file:" + eachFile.getCanonicalPath());
- } else {
- stack.push(eachFile);
- }
- }
- }
- }
- // 文件深度递归遍历
- private static void DFS2(File file) throws IOException {
- System.out.println("dir:" + file.getCanonicalPath());
- File[] files = file.listFiles();
- for (File eachFile : files) {
- if (eachFile.isFile()) {
- System.out.println("file:" + eachFile.getCanonicalPath());
- } else {
- DFS2(eachFile);
-
- }
- }
- }
- // 文件广度非递归遍历
- private static void BFS(File file) throws IOException{
- System.out.println(file.getCanonicalPath());
- Queue< File> queue = new LinkedList< File>();
- queue.offer(file);
- File fileInQueue = null;
- while (queue.size() > 0) {
- fileInQueue = queue.poll();
- //System.out.println("dir--:" + fileInQueue.getCanonicalPath());
- File[] files =fileInQueue.listFiles();
- for (File eachFile : files) {
- if (eachFile.isFile()) {
- System.out.println("file:" + eachFile.getCanonicalPath());
- } else {
- System.out.println("dir--:" + eachFile.getCanonicalPath());
- queue.offer(eachFile);
- }
- }
- }
-
- }
- }
复制代码
源码下载:http://file.javaxxz.com/2014/11/28/000602468.zip |
|