日期:2014-05-20  浏览次数:20835 次

如何实现.txt结尾文件的搜索?
建立一个线程,该线程用来搜索c盘WINDOWS文件夹下所有以“.txt”结尾的文件
(要求:用java实现),最好有注释

------解决方案--------------------
Java code

import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.List;

/**
 * 获取目录下txt文件名
 * @author shangzc
 *
 */
public class UpLoadFile implements FilenameFilter{
    
     private String prefix = "", suffix = "";
     public UpLoadFile(String filterstr) {
      filterstr = filterstr.toLowerCase();
      int i = filterstr.indexOf('*');
      int j = filterstr.indexOf('.');
      if (i > 0) {
       prefix = filterstr.substring(0, i);
      }
      if (j > 0) {
       suffix = filterstr.substring(j + 1);
      }
     }
     public boolean accept(File dir, String name) {
      // TODO Auto-generated method stub
      boolean yes = true;
      try {
       name = name.toLowerCase();
       yes = (name.startsWith(prefix)) & (name.endsWith(suffix));
      } catch (NullPointerException e) {
      }
      return yes;
     }
     /**
      * 得到目下文件的所有的txt
      * @param file
      * @return
      */
     public static List getPhotoName(File file) {
      List fileList = new ArrayList();
      FilenameFilter filter = new UpLoadFile("*.txt");
      File curdir = new File(file.getAbsolutePath(), "");
      String[] str = curdir.list(filter);
      return fileList;
     }
     /**程序的入口*/
     public static void main(String[] args)  {
    
     }
    }

------解决方案--------------------
public class FileFilter implements java.io.FileFilter {
private String regex = "";//such as ".+\\.txt$|"

public FileFilter() {
}
public FileFilter(String[] regex) {
for(String reg : regex) {
this.regex = ".+\\." + reg + "$|" + this.regex;
}
}
@Override
public boolean accept(File pathname) {
// TODO Auto-generated method stub
String tmp=pathname.getName().toLowerCase();
if(this.regex.length()>0)
return (tmp.matches(regex));
return true;
}

}

String[] fileExt = {"txt","scc","avi","mp3"};//列取所有txt,scc,avi,mp3的文件
FileFilter ft = new FileFilter(fileExt);//arg2 is date scope
File file = new File("c:\\");
file.listFiles(filter);



------解决方案--------------------
给个比较简单的:



import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class Test {
List<String> list=new ArrayList<String>();
public List<String> searchText(String folderPath) {
//文件夹路径
File path = new File(folderPath);

String orgsuffix = ".txt";

if (path.exists()) {
//获取目录下的所有文件夹及目录
File[] filePath = path.listFiles();
for (File file : filePath) {
//若是文件
if (file.isFile()) {
String fileName=file.getName();
String suffix = fileName.substring(fileName.length() - 4);
if (orgsuffix.equals(suffix)) {
list.add(fileName);
}
}
//若是文件夹
else if(file.isDirectory()){
//递归
searchText(file.getPath());
}
}
} else {
System.out.println("搜索目录不正确");
}
return list;
}
}