import java.io.File;
import java.util.Iterator;
import edu.princeton.cs.algs4.StdOut;
public class ListFile implements Iterable{
public static void main(String[]args){
ListFile lf=new ListFile("C:\\Users\\0\\Desktop\\testfolder");//test path
for (Object s:lf)
StdOut.println(s);
}
private FileNode first;
private FileNode last;
private int N;
private class FileNode{
String item;
FileNode next;
}
public ListFile(String Path){
ConstructList(Path);
}
private void ConstructList(String Path){
File file=new File(Path);
if (!file.isDirectory()){//is File
FileNode newlast=new FileNode();
newlast.item=file.getName();
if (first==null){
first=newlast;
last=newlast;
}
else {
last.next=newlast;
last=newlast;
}
N++;
}
else {//is Folder
File[] files=file.listFiles();
for (File file1:files)
ConstructList(file1.getPath());
}
}
public Iterator iterator(){
return new ListFileIterator();
}
private class ListFileIterator implements Iterator{
private FileNode current=first;
public boolean hasNext() {
return current!=null;
}
public String next(){
String item=current.item;
current=current.next;
return item;
}
}
}
testfolder文件夹如图
folder1文件夹如图
folder文件夹如图
测试结果 如下: