Java Folder Read by Extension getFiles(String dir, String... extension)

Here you can find the source of getFiles(String dir, String... extension)

Description

get all file which in dir

License

Apache License

Parameter

Parameter Description
dir a parameter
extension a parameter

Declaration

public static List<File> getFiles(String dir, String... extension) 

Method Source Code

//package com.java2s;
//License from project: Apache License 

import java.io.File;

import java.util.ArrayList;
import java.util.List;

public class Main {
    /**//from  www.j  a  v  a 2 s .  c  om
     * get all file which in dir
     * @param dir
     * @param extension
     * @return
     */
    public static List<File> getFiles(String dir, String... extension) {
        File f = new File(dir);
        if (!f.isDirectory()) {
            return null;
        }

        List<File> fileList = new ArrayList<File>();
        getFiles(f, fileList, extension);

        return fileList;
    }

    /**
     * 
     * @param file
     * @param fileList
     * @param extension
     */
    private static void getFiles(File f, List<File> fileList, String... extension) {
        File[] files = f.listFiles();
        if (files == null || files.length == 0) {
            return;
        }
        for (int i = 0; i < files.length; i++) {
            if (files[i].isDirectory()) {
                getFiles(files[i], fileList, extension);
            } else if (files[i].isFile()) {

                String fileName = files[i].getName().toLowerCase();
                boolean isAdd = false;
                if (extension != null) {
                    for (String ext : extension) {
                        if (fileName.lastIndexOf(ext) == fileName.length() - ext.length()) {
                            isAdd = true;
                            break;
                        }
                    }
                }

                if (isAdd) {
                    fileList.add(files[i]);
                }
            }
        }
    }
}

Related

  1. getFiles(File dir, final String extensionFilter)
  2. getFiles(File dir, String fileExtension)
  3. getFiles(File folder, String... extensions)
  4. getFiles(final String path, final String ext)
  5. getFiles(String dir, String ext)
  6. getFiles(String directory, String ext)
  7. getFiles(String path, String _exts)
  8. getFiles(String path, String[] allowedExtension)
  9. getFiles2List(String path, String[] allowedExtension)