package MyTestT;
import java.util.List;
import java.util.ArrayList;
import java.io.*;//抽象类
abstract class AbstractFile {
protected String Name;

public void printName(){
System.out.println(Name);
}
public abstract boolean addChild(AbstractFile file);
public abstract boolean removeChild(AbstractFile file);
public abstract List<AbstractFile> getChildren();
}//文件夹类
class Folder extends AbstractFile {
private List<AbstractFile> childList;
File f1 ;

public Folder(String name){
Name = name;
f1 = new File(Name);
if(f1.mkdir()){
System.out.println("目录创建成功了。");
}
this.childList = new ArrayList<AbstractFile>();
} public boolean addChild(AbstractFile file){
return childList.add(file);
}
public boolean removeChild(AbstractFile file){
return childList.remove(file);
}
public List<AbstractFile> getChildren(){
return childList;
}
}//文件类
class File2 extends AbstractFile {
File f2 ;
public File2(String name){
Name = name;

f2 = new File(Name);
if(f2.mkdir()){
System.out.println("目录创建成功了222。");
}
}
public boolean addChild(AbstractFile file){
return false ;
}
public boolean removeChild(AbstractFile file){
return false ;
}
public List<AbstractFile> getChildren(){
return null;
}
}//测试类
public class Client {
    //主方法
public static void main(String[] args) {
AbstractFile rootFolder = new Folder("C:/Test");
AbstractFile compositeFolder = new Folder("composite");
AbstractFile compositeFolder2 = new Folder("composite2");//
AbstractFile windowFolder = new Folder("windows");
AbstractFile file = new File2("TestComposite.java");

rootFolder.addChild(compositeFolder);
rootFolder.addChild(windowFolder);

compositeFolder.addChild(compositeFolder2);//
compositeFolder.addChild(file);
PrintTree(rootFolder);
}

//构建文件目录树方法
public static void PrintTree(AbstractFile ifile){
ifile.printName();
List<AbstractFile> children = ifile.getChildren();
if(children == null){
return ;
}

for(AbstractFile file2:children){
//file2.printName();
//递归调用,实现对文件子目录的打印
PrintTree(file2);
}
}

}

解决方案 »

  1.   

    为什么我创建的文件夹及文件,只有Test这个文件夹在C盘里,而其它的文件夹及文件怎么都跑到源程序的目录下了,怎么改动呢,能帮我一下吗,大哥哥大姐姐们
      

  2.   

    CSDN有点令人失望,这么久了一个意见都没听到,不过其中的很多问题都得别人的解答,但不是CSDN的人,真希望下次不会这样。
      

  3.   

    只有 C:/Test 是绝对路径。其他的是相对路径