tags:

views:

1286

answers:

3

I need Java code that will parse a given folder and search it for .txt files. Any links or code samples will be helpful.

Thanks, Sri

+1  A: 

Try:

List<String> textFiles(String directory) {
  List<String> textFiles = new ArrayList<String>();
  File dir = new File(directory);
  for (File file : dir.listFiles()) {
    if (file.getName().endsWith((".txt"))) {
      textFiles.add(file.getName());
    }
  }
  return textFiles;
}

You want to do a case insensitive search in which case:

    if (file.getName().toLowerCase().endsWith((".txt"))) {

If you want to recursively search for through a directory tree for text files, you should be able to adapt the above as either a recursive function or an iterative function using a stack.

cletus
Looks good. Let me try this..
Srirangan
A: 

Here is my platform specific code(unix)

public static List<File> findFiles(String dir, String... names)
 {
  LinkedList<String> command = new LinkedList<String>();
  command.add("/usr/bin/find");
  command.add(dir);
  List<File> result = new LinkedList<File>();
  if (names.length > 1)
   {
    List<String> newNames = new LinkedList<String>(Arrays.asList(names));
    String first = newNames.remove(0);
    command.add("-name");
    command.add(first);
    for (String newName : newNames)
     {
      command.add("-or");
      command.add("-name");
      command.add(newName);
     }
   }
  else if (names.length > 0)
   {
    command.add("-name");
    command.add(names[0]);
   }
  try
   {
    ProcessBuilder pb = new ProcessBuilder(command);
    Process p = pb.start();
    p.waitFor();
    InputStream is = p.getInputStream();
    InputStreamReader isr = new InputStreamReader(is);
    BufferedReader br = new BufferedReader(isr);
    String line;
    while ((line = br.readLine()) != null)
     {
      // System.err.println(line);
      result.add(new File(line));
     }
    p.destroy();
   }
  catch (Exception e)
   {
    e.printStackTrace();
   }
  return result;
 }
Milhous
+7  A: 

You can use the listFiles() method provided by the java.io.File class;

import java.io.File;
import java.io.FilenameFilter;

public class Filter {

    public File[] finder( String dirName){
     File dir = new File(dirName);

     return dir.listFiles(new FilenameFilter() { 
              public boolean accept(File dir, String filename)
                   { return filename.endsWith(".txt"); }
     } );

    }

}
djna