package cn.stat.p1.file; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.FilenameFilter; import java.io.IOException; import java.util.ArrayList; import java.util.List; public class textdemo { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub File fl=new File("D:\\java"); FilenameFilter filter=new FilenameFilter(){ @Override public boolean accept(File dir, String name) { // TODO Auto-generated method stub return name.endsWith(".java"); } }; List<File> list=new ArrayList<File>(); getFiles(fl,filter,list); File fos=new File("D:\\java\\info.txt"); wirtefiles(list,fos); } public static void getFiles(File dir,FilenameFilter filter,List<File> list) { File[] files=dir.listFiles(); for(File file : files) { if(file.isDirectory()) { getFiles(file,filter,list); }else { if(filter.accept(file,file.getName())) { list.add(file); } } } } public static void wirtefiles(List<File> list,File desfile) { BufferedWriter bufw=null; try { bufw=new BufferedWriter(new FileWriter(desfile)); for(File file : list) { bufw.write(file.getAbsolutePath()); bufw.newLine(); bufw.flush(); } } catch (IOException e) { // TODO Auto-generated catch block throw new RuntimeException("写不了"); }finally { if(bufw!=null) { try { bufw.close(); } catch (IOException e) { // TODO Auto-generated catch block throw new RuntimeException("关不了"); } } } } }
时间: 2024-12-17 12:10:43