There are two commonly used methods for loading resource files:
1. Use ClassLoader. At this point, I have to mention the classification of ClassLoader. There are three main types of ClassLoader built into Java.
The first is the root class loader (bootstrap class loader), written in C++, which is responsible for loading some key Java classes, such as java.lang.Object and other runtime codes into memory. The package responsible for loading: BootStrp------>JRE/lib/rt.jar
The second is the extended class loader (ExtClassLoader), which is written by java class and is responsible for loading some classes in the JRE into memory. The package responsible for loading: ExtClassLoader---------->JRE/lib/ext/*.jar
The third type is the application class loader (AppClassLoader), or system class loader, which is responsible for loading classes in CLASSPATH into memory. The application class loader can be obtained through ClassLoader.getSystemClassLoader();
Let’s talk about the inheritance of class loaders. Class loaders are not a parent-child relationship of vertical inheritance, but a combination relationship. When instantiating a class loader, the instance of the parent class loader can be passed to the class loader as a construction parameter. in the vessel.
For detailed information about class loaders, you can search by yourself.
After obtaining the application class loader, it is time to obtain the resource file. Call loader.getResource(path) to load the resource file under the corresponding path. It cannot start with '/'. Regarding the resources in the package, you can treat the package as an ordinary folder. , separate each package with '/'.
For example: URL url2 = ClassLoader.getSystemClassLoader().getResource("demo/names.ser"); is to obtain the names.ser serialization file in the demo package.
2. Use the getResource method of the current class that needs to be loaded to load. In fact, this method also calls the class loader that loads this class to obtain the resource file, but the parameters obtained are different.
(1) If you want to get the files in the package where the class is located, you can use relative paths to directly access the resources in the package; for example: Demo1.class.getResource("names.ser"); what you get is the resources in the package where the class file of Demo1 is located.
(2) To obtain resource files outside the package, they must start with '/', such as URL url = Demo1.class.getResource("/demo/names.ser"); what is obtained is the names.ser file in the demo package
In fact, the second method is an encapsulation of the first method, and both use ClassLoader to load resource files. Why do you say that? If you look at the source code of the Class class, you will know: