SoFunction
Updated on 2025-03-01

Java Resource path sorting summary

Java Resource path

First of all, it is very important. There is no standard relative path in Java. Various ways to obtain resources by relative paths are converted into absolute path strength based on certain rules.

Then it is also very important. Never use absolute paths directly, otherwise it will be difficult to see if you die.

Based on the above two points, the problem of Resource path is nothing more than just one point: find the base point, that is, find a stable base point in a certain environment (web, j2ee or jar package, etc.), and then find the resource you want through this base point.

What are the basic points in Java? To summarize, there are several types:

1)classpath

If the resource you are looking for is under classpath, then it is more appropriate to use the base point of classpath, and the way to obtain this base point is mainly through ClassLoader. The specific method is (String name), and there are many ways to obtain ClassLoader, such as:

  1. ().getContextClassLoader()
  2. ()
  3. ClassLoader. getSystemClassLoader()

The implementation principle of ClassLoader's resource search is to recursively load the resource from the classpath in the parent classLoader (how to load the JDK in the end is not open source). If all levels of classLoader are not found, the findResource method is called to find it. This method is exposed to the homemade classLoader for reality, so it gives the opportunity to load resource outside the classpath.

2) Current user directory

It is the path returned relative to ("" ). For general projects, this is the root path of the project. For JavaEE servers, this may be some path to the server. There is no unified norm! However, by default, classes in the package always analyze relative path names based on the current user directory. For example, new File("xxx"), which is to find the xxx file under the ("" ) path. Therefore, there may be porting problems when locateing files in this way.

3) The root directory of the web application

In a web application, we generally obtain the absolute path to the root directory of the web application through the ("/" ) method.

By mastering the above basic points, you can easily locate the resource you are looking for, but you must clearly realize that you should not just seek temporary happiness, regardless of the life or death of the future transplant, and ensure that there is no problem in any environment (j2se or web, windows or Linux).

Thank you for reading, I hope it can help you. Thank you for your support for this site!