io 遍历文件目录并写入文件
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 public class Test { 2 3 /** 4 * @param args 5 */ 6 public static void main(String[] args) { 7 // TODO Auto-generated method stub 8 File dir = new File("E:\\Test\\JAVA"); 9 FilenameFilter filter = new FilenameFilter() { 10 11 @Override 12 public boolean accept(File dir, String name) { 13 // TODO Auto-generated method stub 14 return name.endsWith(".java"); 15 } 16 }; 17 List<File> list = new ArrayList<File>(); 18 getFiles(dir, filter, list); 19 File destFile = new File(dir, "javalist.txt"); 20 writeToFile(list, destFile); 21 22 } 23 /** 24 * 对指定目录中的内容i进行深度遍历,并按照指定过滤器进行过滤 25 * 将过滤器的内容存储到指定容器List中 26 * @param dir 27 * @param filter 28 * @param list 29 */ 30 public static void getFiles(File dir, FilenameFilter filter, List<File> list) { 31 File[] files = dir.listFiles(); 32 for (File file : files) { 33 if (file.isDirectory()) { 34 // 递归查找文件目录 35 getFiles(file, filter, list); 36 } else { 37 // 对遍历到得文件进行过滤器的过滤,将符合条件File对象存储到List集合中 38 if (filter.accept(dir, file.getName())) { 39 list.add(file); 40 } 41 } 42 } 43 } 44 //将List集合存入到文件中 45 public static void writeToFile(List<File> list, File destFile) { 46 BufferedWriter bufx = null; 47 try { 48 bufx = new BufferedWriter(new FileWriter(destFile)); 49 for (File file : list) { 50 bufx.write(file.getAbsolutePath()); 51 bufx.newLine(); 52 bufx.flush(); 53 } 54 } catch (IOException e) { 55 // TODO Auto-generated catch block 56 throw new RuntimeException("写入失败"); 57 } finally { 58 if (bufx != null) { 59 try { 60 bufx.close(); 61 } catch (IOException e) { 62 // TODO Auto-generated catch block 63 throw new RuntimeException("关闭失败"); 64 } 65 } 66 } 67 } 68 69 }