您的位置:首页 > 其它

深度优先与广度优先遍历文件

2012-10-22 15:05 309 查看
package agrisom;

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://Program Files//Common Files//System");

DFSWithStack(file);

System.out.println("--------------------------------");

DFSWithStack2(file);

System.out.println("--------------------------------");

DFS(file);

System.out.println("--------------------------------");

BFSWithQueue(file);

}

/**

* 深度非递归遍历文件

* 缺点是对于同一层次总是先输出所有的文件(子节点),再进行子目录的深度遍历,不太符合顺序

*/

private static void DFSWithStack(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(fileInStack.getCanonicalPath());

File[] files = fileInStack.listFiles();

for (File eachFile : files) {

if (eachFile.isFile()) {

System.out.println(eachFile.getCanonicalPath());

} else {

stack.push(eachFile);

}

}

}

}

/**

* 深度非递归遍历文件

* 保证遍历顺序

*/

private static void DFSWithStack2(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(fileInStack.getCanonicalPath());

File[] files = fileInStack.listFiles();

for (int i=0;files!=null && i<files.length;i++) {

File eachFile=files[i];

if (eachFile.isFile()) {

System.out.println(eachFile.getCanonicalPath());

} else {

//只要访问到子目录,就需要将所有后续子节点入栈

for(int j=i;j<files.length;j++){

stack.push(files[j]);

}

break;

}

}

}

}

//深度递归遍历文件

private static void DFS(File file) throws IOException {

System.out.println(file.getCanonicalPath());

File[] files = file.listFiles();

for (File eachFile : files) {

if (eachFile.isFile()) {

System.out.println(eachFile.getCanonicalPath());

} else {

DFS(eachFile);

}

}

}

//广度非递归遍历文件

private static void BFSWithQueue(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();

File[] files = fileInQueue.listFiles();

for (File eachFile : files) {

if (eachFile.isFile()) {

System.out.println(eachFile.getCanonicalPath());

} else {

System.out.println(eachFile.getCanonicalPath());

queue.offer(eachFile);

}

}

}

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: