Search in a directory wav files
I would like to search开发者_C百科 in a directory if wav files exist.
How can I do that in java?
Thank you.
If you use this:
File dir = new File("/your/dir");
File[] files = dir.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.toLowerCase().endsWith(".wav");
}
});
Then files
will contain an array of File
objects that end with .wav
. If you just want to know if there are any, check if files.length > 0
.
Use File class. It can tell you is it a directory and give a list of files. Then you will be able to analyze the extension using File.getName()
method.
Use FileFilter with File.list()
FileFilter ff = java.io.FileFilter {
public boolean accept(File f) {
String name = f.getName().toLowerCase();
return name.endsWith("wav")
}
dir.list(ff);
Using recursion that shows the files deeper in the directory and where you specify what filetype (for re-usability).
// This collection will contain all the file names
final Collection<File> fileCollection = new ArrayList<File>();
public void addDirectory(File dir, Collection<File> fileCollection, String fileType){
if (fileType == null){
fileType = "";
}
final File[] children = dir.listFiles();
if (children != null){
for(File child : children){
if (child.getName().endsWith(fileType)){
fileCollection.add(child);
}
addDirectory(child, fileCollection, fileType);
}
}
}
You may want to create a filefilter for this specific extension.
FileFilter wavFiter = new FileFilter(){
@Override
public boolean accept(File pathname) {
return pathname.getPath().toLowerCase().endsWith("wav");
}
}
or for any other
class FileExtentionFilter implements FileFilter {
private final String extenstion;
FileExtenstionFilter(String extenstion) {
this.extenstion = extenstion;
}
@Override
public boolean accept(File pathname) {
return pathname.getPath().toLowerCase().endsWith("wav");
}
}
And then use it like this
File dir = new File(dirPath);
File[] waves = dir.listFiles(wavFiter);
or
File dir = new File(dirPath);
File[] waves = dir.listFiles(new FileExtentionFilter("wav"));
精彩评论