Sample in Github
1. Generally use MAVEN to create a Java project, code files in the Src/main/java folder, resource files in the Src/main/resources folder, why can Java code read to the resource file under Src/main/resources?
+ maven will compile the Java project into the target folder,/target/classes should be the root directory. After compiling, the. class file is found in the corresponding subfolder under this folder, and the files under Src/main/resources are copied to this folder.
2. What about the test code in the Src/test/java directory and how to read the resources?
+ Maven compiles the code under the Src/test/java folder into the Target/test-classes folder. Similarly, if you have a resource file under Src/test/resources, copy it to the Target/test-classes folder.
When the test code runs, the resource file under the Test-classes folder is used preferentially, and if it does not exist, the resource file under the Classes folder is used.
public void LoadProperties1 () throws IOException { InputStream input = null; Read from the root folder input = This.getclass (). getResourceAsStream ("/config.properties"); InputStream Java.lang.Class.getResourceAsStream (String name) //1. First, construct an absolute resource path based on the name of the resource // If the resource name is ' /' Start, the absolute name of the resource is '/' after the name part /// Otherwise, that is modified_package_name/name // Modified_package_name is the package name of this class , where the '. ' Change to '/' //2. Then, the rules for finding resources are implemented by class loader of the classes. // If this class is loaded by the Bootstrap class loader, it will use Classloader.getsystemresourceasstream. PrintProperties (input); } public void LoadProperties2 () throws IOException { InputStream input = null; input = This.getclass (). getClassLoader (). getResourceAsStream ("Config2.properties"); The URL java.lang.ClassLoader.getResource (String name) //resource name is the path name of the resource separated by '/'// /First Find parent ClassLoader //If the parent is null, call FindResource (String) printproperties (input) to find the path//failure of the ClassLoader built into the VM;
How Java reads resources