List all files of a specific type

Is there a way to get a list of all files of a certain type with an SDCard? For images, we have Media.Images. Similarly, do we have such a structure below API10?

+7
source share
5 answers

This is my FileFilter for audio files (you can change the list of extensions for your script).

package com.designfuture.music.util;

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

import com.designfuture.framework.util.LogHelper;

public class AudioFileFilter implements FileFilter {

    protected static final String TAG = "AudioFileFilter";
    /**
     * allows Directories
     */
    private final boolean allowDirectories;

    public AudioFileFilter( boolean allowDirectories) {
        this.allowDirectories = allowDirectories;
    }

    public AudioFileFilter() {
        this(true);
    }

    @Override
    public boolean accept(File f) {
        if ( f.isHidden() || !f.canRead() ) {
            return false;
        }

        if ( f.isDirectory() ) {
            return checkDirectory( f );
        }
        return checkFileExtension( f );
    }

    private boolean checkFileExtension( File f ) {
        String ext = getFileExtension(f);
        if ( ext == null) return false;
        try {
            if ( SupportedFileFormat.valueOf(ext.toUpperCase()) != null ) {
                return true;
            }
        } catch(IllegalArgumentException e) {
            //Not known enum value
            return false;    
        }
        return false; 
    }

    private boolean checkDirectory( File dir ) {
        if ( !allowDirectories ) {
            return false;
        } else {
            final ArrayList<File> subDirs = new ArrayList<File>();
            int songNumb = dir.listFiles( new FileFilter() {

                @Override
                public boolean accept(File file) {
                    if ( file.isFile() ) {
                        if ( file.getName().equals( ".nomedia" ) )
                            return false;

                        return checkFileExtension( file );
                    } else if ( file.isDirectory() ){
                        subDirs.add( file );
                        return false;
                    } else
                        return false;
                }
            } ).length;

            if ( songNumb > 0 ) {
                LogHelper.i(TAG, "checkDirectory: dir " + dir.toString() + " return true con songNumb -> " + songNumb );
                return true;
            }

            for( File subDir: subDirs ) {
                if ( checkDirectory( subDir ) ) {
                    LogHelper.i(TAG, "checkDirectory [for]: subDir " + subDir.toString() + " return true" );
                    return true;
                }
            }
            return false;
        }       
    }

    private boolean checkFileExtension( String fileName ) {
        String ext = getFileExtension(fileName);
        if ( ext == null) return false;
        try {
            if ( SupportedFileFormat.valueOf(ext.toUpperCase()) != null ) {
                return true;
            }
        } catch(IllegalArgumentException e) {
            //Not known enum value
            return false;    
        }
        return false; 
    }

    public String getFileExtension( File f ) {
        return getFileExtension( f.getName() );
    }

    public String getFileExtension( String fileName ) {
        int i = fileName.lastIndexOf('.');
        if (i > 0) {
            return fileName.substring(i+1);
        } else 
            return null;
    }

    /**
     * Files formats currently supported by Library
     */
    public enum SupportedFileFormat
    {
        _3GP("3gp"),
        MP4("mp4"),
        M4A("m4a"),
        AAC("aac"),
        TS("ts"),
        FLAC("flac"),
        MP3("mp3"),
        MID("mid"),
        XMF("xmf"),
        MXMF("mxmf"),
        RTTTL("rtttl"),
        RTX("rtx"),
        OTA("ota"),
        IMY("imy"),
        OGG("ogg"),
        MKV("mkv"),
        WAV("wav");

        private String filesuffix;

        SupportedFileFormat( String filesuffix ) {
            this.filesuffix = filesuffix;
        }

        public String getFilesuffix() {
            return filesuffix;
        }
    }

}

You must use FileFilter to get a filtered list of files and directories from a directory:

File[] files = dir.listFiles(new AudioFileFilter());
+15
source

Try entering the code below.

File dir = new File("path to directory");

String[] names = dir.list(
    new FilenameFilter()
    {
        public boolean accept(File dir, String name)
        {
            return name.endsWith(".your file type");
            // Example
            // return name.endsWith(".mp3");
        }
    });

Note that the returned strings are just file names; they do not contain the full path.

+6
source

SD- File:

    File[] file = Environment.getExternalStorageDirectory().listFiles();  


    for (File f : file)
    {
       if (f.isFile() && f.getpath().endswith(".something")) { ... do stuff }
    }
+3

.

If you select some shared files, such as images or videos, use the library.

For any other types, you can try the regular iOS apache library.

Firstly,

dependencies {
    implementation 'commons-io:commons-io:2.5'
}

Then

val iterator = FileUtils.iterateFiles(
    Environment.getExternalStorageDirectory(),
    FileFilterUtils.suffixFileFilter("pdf"),
    TrueFileFilter.INSTANCE)
while (iterator.hasNext()) {
    val fileINeed = iterator.next()
    // do your job
}

As an example, I use the collection of PDF files. It will process sub-dictionaries automatically. Thus, the iterator contains all the PDF files of my device.

Its APIs are very flexible, powerful and easy to use. You can add many filters or rules to complete your XD assignment.

+2
source

I know it's too late, but just in case. I will do it in Kotlin

 val accepted_extention = listOf("mp3", "3gp", "mp4")
 val ROOT_DIR = Environment.getExternalStorageDirectory().absolutePath
 val ANDROID_DIR = File("$ROOT_DIR/Android")
 val DATA_DIR = File("$ROOT_DIR/data")
 File(ROOT_DIR).walk()
               // befor entering this dir check if
               .onEnter{ !it.isHidden // it is not hidden
                         && it != ANDROID_DIR // it is not Android directory
                         && it != DATA_DIR // it is not data directory
                && !File(it, ".nomedia").exists() //there is no .nomedia file inside
               }.filter { accepted_extention.indexOf(it.extension) > -1}// it is of accepted type
               .toList()
0
source

All Articles