I am currently creating a continuation of the java series on useing reflection. In one of the examples I was trying to read from a properties file. I completely forgot how to find the resource I was looking for. I found this article on Java World. It’s from 2003, but still relevent.
To start with. The myFile.properties file is in the same package as the class MyClass.
These were my attempts:
// 1. Just get a FileInputStream InputStream aStream = new FileInputStream("myFile.properties"); // 2. Switched to getResourceAsStream InputStream aStream = MyClass.class.getClassLoader().getResourceAsStream("my/package/myProps.properties"); // 3. Settled on InputStream aStream = MyClass.class.getResourceAsStream("myProps.properties");
So, the first attempt was me completely forgetting how to do things. The only way that works is if you are putting in an absolute path from the file system. Never a good idea.
The second one, using the ClassLoader went astray because I forgot to include the “/” at the beginning.
The third times a charm. If you get the resource right from the class, you can also use relative pathing, and I got to drop the path.
That works much better.