简体   繁体   中英

List all files in resources directory in java project

I want to list all files in resources classpath ,I used the following code but get null exception in fList

在此输入图像描述

 String path = request.getSession().getServletContext().getRealPath("/resources/rules");
    File directory = new File(path);
    File[] fList = directory.listFiles();
    for (File file : fList){
        if (file.isFile()){
            System.out.println(file.getName());
        }
    }

Here is a working example:

https://github.com/bleujin/aradon/blob/master/src/net/ion/nradon/helpers/ClassloaderResourceHelper.java#L30

public static Iterable<FileEntry> listFilesRelativeToClass(Class<?> clazz, String subdirectory) throws IOException {
    ArrayList<FileEntry> list = new ArrayList<FileEntry>();
    CodeSource src = clazz.getProtectionDomain().getCodeSource();
    if (src == null) {
        return list;
    }
    URL classpathEntry = src.getLocation();
    try {
        // Check if we're loaded from a folder
        File file = new File(new File(classpathEntry.toURI()), subdirectory);
        if (file.isDirectory()) {
            return fileEntriesFor(file.listFiles());
        }
    } catch (URISyntaxException e) {
        // Should never happen, because we know classpathentry is valid
        throw new RuntimeException(e);
    }

    // We're not in a folder, so we must be in a jar or similar
    subdirectory = subdirectory.replace(File.separatorChar, '/');
    if (!subdirectory.endsWith("/")) {
        subdirectory = subdirectory + "/";
    }

    ZipInputStream jarStream = new ZipInputStream(classpathEntry.openStream());
    ZipEntry zipEntry;
    while ((zipEntry = jarStream.getNextEntry()) != null) {
        if (isChild(subdirectory, zipEntry.getName())) {
            String basename = zipEntry.getName().substring(subdirectory.length());
            int indexOfSlash = basename.indexOf('/');
            if (indexOfSlash < 0 || indexOfSlash == basename.length() - 1) {
                list.add(new FileEntry(basename));
            }
        }
    }
    return list;
}

private static boolean isChild(String parent, String name) {
    return name.startsWith(parent);
}

public static Iterable<FileEntry> fileEntriesFor(File[] files) {
    List<FileEntry> fileEntries = new ArrayList<FileEntry>(files.length);
    for (File file : files) {
        String filename = file.getName();
        if (file.isDirectory()) {
            filename += "/";
        }
        fileEntries.add(new FileEntry(filename));
    }
    return fileEntries;
}

}

How about this source code?

 String[] resoures = srcDir.list( new java.io.FilenameFilter()
        {
            public boolean accept( File dir, String name )
            {
                String[] extensions = { ".png", ".jar", ".txt" };
                String fileName = name.toLowerCase( Locale.getDefault() );
                for ( int i = 0; i < extensions.length; i++ )
                {
                    if ( fileName.endsWith( extensions[i] ) )
                    {
                        return true;
                    }
                }
                return false;

            }
        } );

Full source here:

http://code.openhub.net/file?fid=kpl9VrAT-CHXE496rmMP8Jbzo5U&cid=y9kXCqEmUoY&s=List%20all%20files%20in%20resoures%20directory%20in%20java%20project&pp=0&fl=Java&ff=1&projSelected=false&filterChecked,=true&mp,=1&mp=1&ml=1&me=1&md=1#L64

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM