1 package FileDemo; 2 3 import java.io.BufferedWriter; 4 import java.io.File; 5 import java.io.FileWriter; 6 import java.io.FilenameFilter; 7 import java.io.IOException; 8 import java.util.ArrayList; 9 import java.util.List; 10 11 public class FilePropertyTest { 12 13 /** 14 * @param args 15 * @throws IOException 16 */ 17 public static void main(String[] args) throws IOException { 18 19 File dir = new File("D:\Java"); 20 FilenameFilter filter = new FilenameFilter() { 21 22 @Override 23 public boolean accept(File dir, String name) { 24 25 return name.endsWith(".txt"); 26 } 27 }; 28 List<File> list = new ArrayList<File>(); 29 getFiles(dir, filter, list); 30 File destFile = new File("D:\destfile.txt"); 31 write2File(list, destFile); 32 } 33 34 public static void getFiles(File dir, FilenameFilter fileter, 35 List<File> list) { 36 File files[] = dir.listFiles(); 37 for (File file : files) { 38 if (file.isDirectory()) { 39 getFiles(file, fileter, list); 40 } else { 41 if (fileter.accept(dir, file.getName())) { 42 list.add(file); 43 } 44 } 45 } 46 } 47 48 public static void write2File(List<File> list, File destFile) throws IOException { 49 BufferedWriter bufw = null; 50 try { 51 bufw = new BufferedWriter(new FileWriter(destFile)); 52 for (File file : list) { 53 bufw.write(file.getAbsolutePath()); 54 bufw.newLine(); 55 bufw.flush(); 56 } 57 } catch (Exception e) { 58 throw new RuntimeException("出现异常,写入失败"); 59 } finally { 60 if(bufw!=null){ 61 try { 62 bufw.close(); 63 64 } catch (Exception e2) { 65 66 throw new RuntimeException("关闭失败"); 67 } 68 } 69 } 70 } 71 72 }