Java Folder Read by Extension getFilesWithExtension(String directory, String extension)

Here you can find the source of getFilesWithExtension(String directory, String extension)

Description

get an array of all files in the given directory, with given extension

License

Open Source License

Parameter

Parameter Description
directory the full path directory to check
extension the extension to find

Return

an array of all file names in that directory (without full path)

Declaration

public static String[] getFilesWithExtension(String directory, String extension) 

Method Source Code

//package com.java2s;

import java.io.File;

import java.util.ArrayList;

import java.util.List;

import java.util.Vector;

public class Main {
    /**// w w w. ja v a  2s .  co m
     * get an array of all files in the given directory, with given extension
     * 
     * @param directory
     *            the full path directory to check
     * @param extension
     *            the extension to find
     * @return an array of all file names in that directory (without full path)
     */
    public static String[] getFilesWithExtension(String directory, String extension) {
        Vector<String> vector = new Vector<String>();
        File f = new File(directory);
        File[] files = f.listFiles();
        for (int i = 0; i < files.length; i++) {
            if (files[i].getName().endsWith(extension)) {
                vector.add(files[i].getName());
            }
        }
        String[] toReturn = new String[vector.size()];
        vector.toArray(toReturn);
        return toReturn;
    }

    public static String[] listFiles(String fileName) {
        return listFiles(new File(fileName));
    }

    public static String[] listFiles(File file) {
        List<String> files = new ArrayList<String>();

        File[] fileArray = file.listFiles();
        if (fileArray != null) {
            for (int i = 0; i < fileArray.length; i++) {
                if (fileArray[i].isFile()) {
                    files.add(fileArray[i].getName());
                }
            }
        }

        return (String[]) files.toArray(new String[0]);
    }
}

Related

  1. getFilesFiteredByExtension(final File parent, final List extensions)
  2. getFilesForType(final File target, final String extension)
  3. getFilesFromExtension(String directory, String[] extensions)
  4. getFilesWithExtension(File aDirectory, final String aExtension)
  5. getFilesWithExtension(File dir, String extension)
  6. getFilesWithinPath(File path, String fileExtension)