如何获取给定目录中的文件路径和子文件夹中的文件?

时间:2015-12-15 21:58:49

标签: java directory subdirectory

我有Fayl和Folder类,它扩展了FSComponent抽象类,它有add,setName和print方法。我想打印所有文件'给定目录中的路径,包括子文件夹中的文件。但在我的主要内容中,它只打印文件和子文件夹的pathes而不包含子文件夹的文件。我怎样才能打印子文件夹的文件?

抽象类

public abstract class FSComponent {

protected String name;

public void add(FSComponent c) {
    throw new UnsupportedOperationException();
}
public void setName(String name) {
    this.name = name;
}
public void print() {
    throw new UnsupportedOperationException();
}
}

文件夹

 public class Folder extends FSComponent{
 ArrayList<FSComponent> list;

public Folder(String name) {
    list = new ArrayList<FSComponent>();
    this.name = name;
}

public void add(FSComponent c) {
    list.add(c);}
public void print() {
for (FSComponent c : list)
c.print();}}

文件

public class Fayl extends FSComponent {
public Fayl(String name) {
    this.name = name;}
public void print() {
System.out.println("File: "+name);}}

主要

public class main2 {

static Folder main;
public static void listk(String path){
    File folder = new File(path);
     main=new Folder(path);
    File[] listOfFiles = folder.listFiles();

        for (int i = 0; i < listOfFiles.length; i++) {
          if (listOfFiles[i].isFile()) {

            String path1=listOfFiles[i].getAbsolutePath();
            main.add(new Fayl(listOfFiles[i].getAbsolutePath()));

          } else if (listOfFiles[i].isDirectory()) {

            main.add(new Folder(listOfFiles[i].getAbsolutePath()));}  }}
public static void main(String[] args) {
listk("C:\\Users\\user\\Pictures");}}

0 个答案:

没有答案