package main; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayList; /** * @author 周广 * @version 1.0 * @Time 2016/02/20 * @see 类的唯一构造函数接收一个字符串格式的文件夹路径,以此构建一个对象。 * 通过调用 init()方法,判断这个路径是否存在且是否为文件夹。 * init()方法会在验证路径通过后调用showAll()方法获取这个路径下所有文件的路径(包括子文件夹) * 最后通过调用backAllFilePath()方法返回装载所有File对象的容器 */ public class ShowAllFile { //用于存放传入的路径 private String path; //用于构建传入的路径的File对象 private File file; //用于存放所有的File对象 private ArrayList<File> fileList; /** * 带参构造函数(唯一) * @param path */ public ShowAllFile(String path) { this.path=path; } /** * * @return 返回一个装载了扫描到的所有的File对象的容器 */ public ArrayList<File> backAllFilePath() { return fileList; } /** * * @throws FileNotFoundException 如果传入的路径不正确抛出异常 * @throws IOException 如果传入的路径指向的不是一个文件夹抛出异常 * @see 验证传入的文件夹路径,在验证成功后调用showAll()方法处理路径 */ public void init() throws FileNotFoundException,IOException { file=new File(path); if (!file.exists()) { throw new FileNotFoundException(path); }else { if (!file.isDirectory()) { throw new IOException(); }else { fileList=new ArrayList<File>(); showAll(file); } } } /** * @param 已经被验证的File对象 * @see 私有方法被init()调用,来递归处理文件夹及子文件夹 */ private void showAll(File file){ File files[]=file.listFiles(); for (File f : files) { if (!f.isDirectory()) { fileList.add(f); }else { showAll(f); } } } }
原文:http://www.cnblogs.com/augustus-chou/p/5204432.html