user838522
user838522

Reputation: 3991

Filter file array based on the file extensions

I have the following code:

File dir = new File("/sdcard/LOST.DIR");
final File file[]=dir.listFiles();

And the file[] array here contains a list of all the files present in the dir. I want to create another file[] array based on file extensions. Ex: this new array should contain the list of all image files only (ending with .jpg / .png / .tif etc) and it should exclude other files.

How do I achieve this?

Upvotes: 1

Views: 4696

Answers (3)

Pankti
Pankti

Reputation: 419

Try doing this. It may help filter files with provided extensions:

import java.io.*;
abstract class Test implements FileFilter{
    public static void main(String[] args){
        File f = new File(args[0]);
        final String[] okFileExtension = new String[]{"jpg","png","gif","pdf"};
        File name[] = f.listFiles(new FileFilter(){
            public boolean accept(File file){
                for(String extension : okFileExtension){
                    if(file.getName().endsWith(extension))
                        return true;
                }
                return false;
            }
        });
    }
}

Upvotes: 1

Vladimir
Vladimir

Reputation: 3812

You can try something like this to find files:

public void processDirectory(File aFile)
{
   if (aFile.isFile()) 
   {
       processFile(aFile);
   } else if (aFile.isDirectory()) {            
   File[] listOfFiles = aFile.listFiles();
   if (listOfFiles != null) {
      for (int i = 0; i < listOfFiles.length; i++)
         processDirectory(listOfFiles[i]);
   } else {
      Log.d(TAG, " [ACCESS DENIED]");
   }
}
}

public void processFile(File aFile) 
{
try 
{
if (!aFile.getName().endsWith(".mp3"))
return;
//Add file path to another array of files
}
}

and now you can do like this:

File dir = new File("/sdcard/LOST.DIR");
processDirectory(dir)

UPDATE: for example you can declare

ArrayList<String> = filesPath new ArrayList<String>();

and in processFile:

filesPath.Add(aFile.getAbsolutePath());

and at the end you can get array like this:

filesPath.toArray();

Upvotes: 1

user370305
user370305

Reputation: 109237

You can use Java File methods for this, (I never try this)

 File[] listFiles(FileFilter filter)

Returns an array of abstract pathnames denoting the files and directories in the directory denoted by this abstract pathname that satisfy the specified filter.

File[] listFiles(FilenameFilter filter)

Returns an array of abstract pathnames denoting the files and directories in the directory denoted by this abstract pathname that satisfy the specified filter.

Look at this nice JAVA File Filter example Filter Files in Java

Upvotes: 0

Related Questions