import java.io.File; import java.io.IOException; public class FileUtilTest { public static void listDirectory(File dir) throws IOException { if (!dir.exists()) { throw new IllegalArgumentException("目录" + dir + "不存在"); } if (!dir.isDirectory()) { throw new IllegalArgumentException(dir + "不是目录"); } File[] files = dir.listFiles(); if (files!=null && files.length>0) { for (File file : files) { if (file.isDirectory()) { //递归 listDirectory(file); } else { System.out.println(file); } } } } public static void main(String[] args) throws IOException { listDirectory(new File("C:\\Windows")); } }
使用递归的方式对某个目录进行遍历。
部分运行结果如图:
原文:http://my.oschina.net/donngchao/blog/526493