4.2.6.4. Resources
Resources
interface maintains resources loading according to the following rules:
-
If the provided location is a URL, the resource is downloaded from this URL;
-
If the provided location begins with
classpath:
prefix, the resource is downloaded from classpath; -
If the location is not a URL and it does not begin with
classpath:
, then:-
The file is searched in the configuration folder of application using the provided location as relative pathname. If the file is found, the resource is downloaded from it;
-
If the resource is not found at the previous steps, it is downloaded from classpath.
-
In practice, explicit identification of URL or classpath:
prefix is rarely used, so resources are usually downloaded either from the configuration folder or from classpath. The resource in the configuration folder overrides the classpath resource with the same name.
Resources
methods:
-
getResourceAsStream()
– returnsInputStream
for the provided resource, ornull
, if the resource is not found. The stream should be closed after it had been used, for example:@Inject protected Resources resources; ... InputStream stream = null; try { stream = resources.getResourceAsStream(resourceLocation); ... } finally { IOUtils.closeQuietly(stream); }
You can also use "try with resources":
try (InputStream stream = resources.getResourceAsStream(resourceLocation)) { ... }
-
getResourceAsString()
– returns the indicated resource content as string, ornull
, if the resource is not found.