What is the difference between getClass().getClassLoader().getResource() and getClass.getResource()?
When retrieving files from resources, which one should I use in what circumstances?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The second one calls the first one. The difference is described in the javadoc.
The first one takes paths that don’t start with a
/, and always starts at the root of the classpath.The second one takes path that can start with a
/. If it does, it starts at the root of the classpath. If not, it starts at the package of the class on which the method is called.So
getClass().getClassLoader().getResource("foo/bar.txt")is equivalent togetClass().getResource("/foo/bar.txt").And, assuming getClass() returns a class that is in the package
foo,getClass().getResource("bar.txt")is equivalent togetClass().getClassLoader().getResource("foo/bar.txt")