ResourceUtil
Introduction
ResourceUtil
provides encapsulation for fast reading of resources.
Usage
The core method in ResourceUtil
is getResourceObj
. This method returns different implementations based on whether the passed path is an absolute path. For example, paths such as file:/opt/test
and /opt/test
are treated as absolute paths, causing FileResource
to be invoked to read the data. If the conditions are not met, ClassPathResource
is invoked by default to read resources or files from the classpath.
Similarly, this utility class also encapsulates readBytes
and readStr
for quick reading of bytes and strings.
For example, assuming we have a test.xml
file in the classpath, reading it becomes very simple:
String str = ResourceUtil.readUtf8Str("test.xml");
If our file is located in the src/resources/config
directory, the reading should be modified as follows:
String str = ResourceUtil.readUtf8Str("config/test.xml");
Note:
In IntelliJ IDEA, if you add a new file to the src/resources
directory, you need to reimport the project to ensure that the resource file is successfully copied to the target directory during compilation. If an error is encountered stating that the file cannot be found, please confirm whether the file exists in the target directory.