Today I found something that, although very subtle, helped me to get out weird behaviors.

I’m working in a Twitter API written in java and needed to load a configuration file from a package among my source code. So I tried with this.getClass().getResourceAsStream(filename) but wasn’t being able to get it, so I googled some about it and found something very interesting.
The code this.getClass().getResourceAsStream(filename) only looks for a file on the same directory of the .class file. To load a file that’s somewhere within the enrire classpath do this.getClass().getClassLoader().getResourceAsStream(filename).

When you stop a second and think about the first piece of code you see that this behavior is more logic than what you were expecting.

For those who don’t understand how did they do it take a look inside the code from the Class class.
The getResourceAsStream(String) method calls a resolveName(String) method that actually append to the string parameter the path of the class itself. So that’s why you only can load files from the .class directory.

Hopes it can help some one with the same doubts that I had.

Some people say that the first impression is decisive, and if it is true I must have been trully disappointed with Java.

Actually I have been.

I came from the Microsoft C# edge and by far I’m not judging their way of explaining things easier, but the way Java keep forcing you to dirty your hands with silly repetitive codes and the way the community say to you “If you don’t like, go back to VB” help you when you try to explain your doubts is not the easiest way of hearing a Hello. Read the rest of this entry »