Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

looking for txt file in a directory

Status
Not open for further replies.
Jun 19, 2001
86
0
0
US
I need to be able to read the contents of a directory into an array. The elements should only equal files that end in .txt. For instance if the directory contains 1.txt, 2.txt, 3.txt, and 4.htm the array should contain 3 elements. I have been fumbling with the endsWith("txt") method but haven't had any luck. Thanks in advance!

Nathan
 
Hi Nathan,

you can use a FileFilter to do just that, here's an example:

C:\test>more ListFiles.java
import java.io.*;
import java.util.*;

public class ListFiles {
public static void main(String[] args){
File f = new File(args[0]);
if(f.exists()){
if(f.isDirectory()){
TextFileFilter filter = new TextFileFilter();
File[] files = f.listFiles(filter);
System.out.println(Arrays.asList(files));
}else{
System.out.println("Please enter a valid directory!");
}
}
}
}

class TextFileFilter implements FileFilter{
public boolean accept(File file){
if(file.getName().toLowerCase().endsWith("txt")){
return true;
}
return false;
}
}

C:\test>dir c:\test\testfiles
Volume in drive C has no label.
Volume Serial Number is 5878-C071

Directory of c:\test\testfiles

14/08/2003 16:25 <DIR> .
14/08/2003 16:25 <DIR> ..
14/08/2003 16:25 0 a.txt
14/08/2003 16:25 0 b.txt
14/08/2003 16:25 0 c.txt
14/08/2003 16:25 0 d.htm
4 File(s) 0 bytes
2 Dir(s) 37,420,462,080 bytes free

C:\test>java ListFiles c:\test\testfiles
[c:\test\testfiles\a.txt, c:\test\testfiles\b.txt, c:\test\testfiles\c.txt]

C:\test>
 
Would it be possible to do this without the separate TextFile filter class?

Nathan
 
Or a bit shorter :
Code:
  public class TextFileFilter implements FileFilter{
    public boolean accept(File file){
      return file.getName().toLowerCase().endsWith(&quot;txt&quot;);
    }
  }

Or even shorter if you use an anonymous inner class
Code:
File[] files = f.listFiles(new FileFilter() {
   public boolean accept(File file){
     return file.getName().toLowerCase().endsWith(&quot;txt&quot;);
   }
});

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top