I just came across some peculiar behavior with getResourceAsInputStream that I was hoping someone could shed some light on.
Passing this method the name of a nonexistent resource returns null, like I'd expect. However, passing it an empty or space-filled string actually returns a valid InputStream with zero bytes in it. Only empty or space-filled strings seem to do this; whitespace like "\t" or "\n" will result in a null.
Is this intended behavior? If so, what is it's purpose?
this.class.getResourceAsStream("no_such_resource"); // returns null
this.class.getResourceAsStream(""); // returns an InputStream
this.class.getResourceAsStream(" "); // returns an InputStream
this.class.getResourceAsStream("\t"); // returns null
getResourceAsStream
asks the ClassLoader to construct a URL for the path. The path with an empty string or blanks at the end points to the directory of files where your classes .class file resides, so it constructs a FileURLConnection
object. getResourceAsStream
in turn asks that object to getInpuStream()
and the implementation builds up a sorted directory listing in a string, converts it to bytes according to the default locale and gives you a ByteArrayInputStream
on these bytes.
FileURLConnections behaviour is not very well documented, but if your search...
Try this code:
InputStream is = this.class.getResourceAsStream("");
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line;
while((line = br.readLine()) != null) System.out.println(line);
br.close();
this will print a list of classes that are located in the same directory of the current class. For example:
a.class
CallablePrintTask.class
java.policy.applet
RunnablePrintTask.class
ZoomableImageFrame.class
ZoomableImageFrame$FlagHolder.class
ZoomableImageFrame$ImageViewer.class
ZoomableImageFrame$LoadAction.class
ZoomableImageFrame$LoadAction$1.class
ZoomableImageFrame$ScaleAction.class
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With