我想列出资源类路径中的所有文件,我使用了以下代码但在fList中获取了null异常
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());
}
}
答案 0 :(得分:0)
这是一个有效的例子:
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;
}
}
答案 1 :(得分:0)
这个源代码怎么样?
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;
}
} );
完整来源: