Java Folder Read by Extension getFiles(String directory, String ext)

Here you can find the source of getFiles(String directory, String ext)

Description

Get the list of specific file types in a directory

License

Open Source License

Parameter

Parameter Description
directory The directory
ext the file extension

Return

File name list

Declaration

public static List<String> getFiles(String directory, String ext) 

Method Source Code

//package com.java2s;
/* Copyright 2012 Yaqiang Wang,
* yaqiang.wang@gmail.com/*w ww .j  a va 2  s .  c  om*/
* 
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or (at
* your option) any later version.
* 
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser
* General Public License for more details.
*/

import java.io.File;

import java.util.ArrayList;

import java.util.List;

public class Main {
    /**
     * Get the list of specific file types in a directory
     *
     * @param directory The directory
     * @param ext the file extension
     * @return File name list
     */
    public static List<String> getFiles(String directory, String ext) {
        List<String> fileNames = new ArrayList<>();
        try {
            File f = new File(directory);
            boolean flag = f.isDirectory();
            if (flag) {
                File fs[] = f.listFiles();
                for (int i = 0; i < fs.length; i++) {
                    if (!fs[i].isDirectory()) {
                        String filename = fs[i].getAbsolutePath();
                        if (filename.endsWith(ext.trim())) {
                            fileNames.add(filename);
                        }
                    } else {
                        fileNames.addAll(getFiles(fs[i].getAbsolutePath(), ext));
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return fileNames;
    }
}

Related

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