import java.io.*;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/**
* 读取目录及子目录下指定文件名的路径 并放到一个数组里面返回遍历
* @author
*
*/
public class FileViewer {
//public static
/**
*
* @param path 文件路径
* @param suffix 后缀名
* @param isdepth 是否遍历子目录
* @return
*/
public static int getListFiles(List<String> filelist,String path, String suffix, int maxDepth,boolean incSubDirs)
{
File file = new File(path);
int curDepth=0;
//int filecount=0;
return FileViewer.listFile(filelist,file ,suffix, curDepth,maxDepth,incSubDirs);
}
private static int listFile(List<String> filelist,File f, String suffix,int curDepth,int maxDepth,boolean incSubDirs)
{
//是目录,同时需要遍历子目录
int totalCount=0;
if (f.isDirectory())
{
if(curDepth<maxDepth||maxDepth<=0)
{
File[] t = f.listFiles();
for (int i = 0; i < t.length; i++)
{
if(incSubDirs&&t[i].isDirectory())
{
filelist.add(t[i].getAbsolutePath());
totalCount++;
}
totalCount+=listFile(filelist,t[i], suffix, curDepth+1,maxDepth,incSubDirs);
}
}
}
else
{
String filePath = f.getAbsolutePath();
//System.out.println("suffix = "+suffix);
if("".equals(suffix)|| suffix == null)
{
//后缀名为null则为所有文件
//System.out.println("----------------");
filelist.add(filePath);
totalCount++;
}
else
{
int begIndex = filePath.lastIndexOf(".");//最后一个.(即后缀名前面的.)的索引
String tempsuffix = "";
if(begIndex != -1)//防止是文件但却没有后缀名结束的文件
{
tempsuffix = filePath.substring(begIndex + 1, filePath.length());
}
if(tempsuffix.equals(suffix))
{
filelist.add(filePath);
totalCount++;
}
//System.out.println("|||||||||||||||||||");
}
}
return totalCount;
}
public static void main(String[] argv){
String f = ("E:\\新建文件夹 (4)\\trunk\\02 开发库\\0204.编码\\NetEyeVPNClient");
String java=null;
FileViewer aa=new FileViewer();
List<String> fileList = new ArrayList<String>();
int count=aa.getListFiles(fileList,f,java, 0,false);
for(int i=0;i<fileList.size();i++)
{
System.out.println(fileList.get(i));
}
}
}