Java 获取指定文件夹下特定后缀名的所有文件

import java.io.File;
import java.io.FileFilter;

/**
 * This class can take file's path and file's name;
 * you must give the path where you want to take the file. 
 */
public class App 
{
    public static void main( String[] args )
    {
        // This is the path where the file's name you want to take.
        String path = "D:\\Test";
        getFile(path);
    }

    private static void getFile(String path){
        // get file list where the path has
        File file = new File(path);
        // get the folder list
        File[] array = file.listFiles(new FileFilter() {
            @Override
            public boolean accept(File pathname) {
                return pathname.getName().endsWith(".JPG");
            }
        });

        if(array.length != 0) {
            for (File value : array) {
                if (value.isFile()) {
                    // only take file name
                    System.out.println("^^^^^" + value.getName());
                    // take file path and name
                    System.out.println("#####" + value);
                    // take file path and name
                    System.out.println("*****" + value.getPath());
                } else if (value.isDirectory()) {
                    getFile(value.getPath());
                }
            }
        }
    }
}

上面的代码是获取 D 盘 Test 目录下.JPG后缀的文件名。


参考资料:java获取指定文件夹下的所有文件名
Excluding system files in file.lists() in java
Java FileFilter (with Examples)

标签: none

评论已关闭