Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does getResourceAsStream with an empty string return an empty InputStream?

Tags:

java

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
like image 618
Joel McCance Avatar asked Jul 13 '12 16:07

Joel McCance


2 Answers

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...

like image 128
Arne Avatar answered Oct 22 '22 02:10

Arne


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
like image 21
Eng.Fouad Avatar answered Oct 22 '22 01:10

Eng.Fouad