Various answers (e.g. Get a list of resources from classpath directory) indicate that if you call getResourceAsStream
on a directory, the returned stream will contain a list of items in the directory, one per line. This doesn't appear to be documented in the ClassLoader Javadoc. Is it specified anywhere else, or is it just an implementation detail that people have come to rely on?
1 Answers
It doesn't look like this is appropriately documented anywhere.
From the Javadoc of ClassLoader.getResourceAsStream
you can somewhat infer that getResourceAsStream
is the same as doing getResource
and then calling URL.openStream
on the resulting URL, because the Javadoc points to the getResource
method, which returns URL
. But its clearly not spelled out to that degree of accuracy.
public InputStream getResourceAsStream(String name)
Returns an input stream for reading the specified resource. The search order is described in the documentation for
getResource(String)
.
Then, URL.openStream
is documented better:
public final InputStream openStream() throws IOException
Opens a connection to this URL and returns an InputStream for reading from that connection. This method is a shorthand for:
openConnection().getInputStream()
Then, since URL.openConnection()
returns a subclass of URLConnection
, and assuming that you used a local directory in your classpath, you need to look at FileURLConnection
, and then in the method getInputStream
.
As you can see in the method below, if the file:///
URL from the classpath points to a directory, then it returns an InputStream
with all the files in the directory in a sorted manner. (Interesting detail, it uses the platform default encoding - good to know when you want to read the data back)
public synchronized InputStream getInputStream()
throws IOException {
int iconHeight;
int iconWidth;
connect();
if (is == null) {
if (isDirectory) {
FileNameMap map = java.net.URLConnection.getFileNameMap();
StringBuffer buf = new StringBuffer();
if (files == null) {
throw new FileNotFoundException(filename);
}
Collections.sort(files, Collator.getInstance());
for (int i = 0 ; i < files.size() ; i++) {
String fileName = files.get(i);
buf.append(fileName);
buf.append("\n");
}
// Put it into a (default) locale-specific byte-stream.
is = new ByteArrayInputStream(buf.toString().getBytes());
} else {
throw new FileNotFoundException(filename);
}
}
return is;
}
Conclusion:
It's not properly documented, it's an implementation detail, it could change in future releases, although that's not likely.

- 30,799
- 15
- 56
- 79
-
Thanks, and that also explains why you can't list directories in JAR files in this manner: the [JarURLConnection](http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8-b132/sun/net/www/protocol/jar/JarURLConnection.java?av=f) class doesn't have that functionality. – mhsmith May 13 '17 at 16:24