怎么得到文件目录的树形数据结构
如何得到文件目录的树形数据结构
假设给定文件目录集合于list<string>中,如何得到这样一个tree呢
如:/A/A1/A11
/A/A1/A12
/A/A2
如何得到如下的树呢
A
A1 A2
A11 A12
谢谢
------解决方案--------------------
public int insert(String name){
Node node = new Node(name, 1, null, null);
int source = this.name.compareTo(name);
if(source < 0){
if(this.left == null){
this.left = node;
return -1;
}else{
this.left.insert(name);
}
}
else if(source > 0){
if(this.right == null){
this.right = node;
return 1;
}else{
this.right.insert(name);
}
}
else{
this.count++;
return 0;
}
return 2;
}
------解决方案--------------------
应该有API可使用
------解决方案--------------------
“假设给定文件目录集合于list<string>中”这个假设就不对吧?只需要根节点就够了。看你的要的结果应该是层次结构,一次BFS即可解决:
假设给定文件目录集合于list<string>中,如何得到这样一个tree呢
如:/A/A1/A11
/A/A1/A12
/A/A2
如何得到如下的树呢
A
A1 A2
A11 A12
谢谢
------解决方案--------------------
public int insert(String name){
Node node = new Node(name, 1, null, null);
int source = this.name.compareTo(name);
if(source < 0){
if(this.left == null){
this.left = node;
return -1;
}else{
this.left.insert(name);
}
}
else if(source > 0){
if(this.right == null){
this.right = node;
return 1;
}else{
this.right.insert(name);
}
}
else{
this.count++;
return 0;
}
return 2;
}
------解决方案--------------------
应该有API可使用
------解决方案--------------------
“假设给定文件目录集合于list<string>中”这个假设就不对吧?只需要根节点就够了。看你的要的结果应该是层次结构,一次BFS即可解决:
import java.io.File;
import java.util.LinkedList;
import java.util.Queue;
/**
*
普通树的结点
*/
class FileNode<T>{
/** 数据域 */
T t;
/** 所属层*/
int ceng;
public FileNode(T t, int ceng) {
super();
this.t = t;
this.ceng = ceng;
}
@Override
public String toString() {
return "FileNode [t=" + t + ", ceng=" + ceng + "]";
}
}
public class ListFile {
/**
* 广度遍历文件夹结构
*/
public static void listFile(String fileName){
File dir=new File(fileName);
FileNode<File> root=new FileNode<File>(dir, 1);
Queue<FileNode<File>> que=new LinkedList<FileNode<File>>();
que.offer(root);
int ceng=1;
FileNode<File> p=null,child=null;
File[] childs=null;
while(!que.isEmpty()){
p=que.poll();
if(p.ceng>ceng){
//换层
System.out.println();
ceng++;
}
System.out.print(p.t.getName()+" ");
if(p.t.isDirectory()){
childs=p.t.listFiles();
for(File f:childs){
child=new FileNode<File>(f, p.ceng+1);
que.offer(child);
}
}
}
}
public static void main(String[] args) {
listFile("D:\\Program Files\\MyEclipse\\workspace\\JavaProject\\src");
}
}