How to get a specific file in the resouces directory has been explained in many articles on the Internet. But sometimes we need to get the absolute address of the resouces directory, for example, when using the FreeMarker template engine, we need to set the directory where the template is loaded. This article describes three methods.
- Obtained through the relative directory and the File API
The code is as follows:
1 | String path = "src/main/resources/templates"; |
- Obtained through relative directories and the Path API after Java 7
1 | Path templateFolder = Paths.get("src", "main", "resources", "templates"); |
- Obtained indirectly by specifying a specific file
Obtained indirectly through a concrete file in resouces. For example: Let’s put a file named logback .xml in the resources directory, using the following code
1 | String resouceName = "logback.xml"; |
Eventually, with file.getParent(), we can get the absolute address of the directory where the file is located (i.e. the resources directory), and the file handle to the resources directory can be obtained via file.file.getParentFile().
The last method is recommended because the variables “src”, “main”, “resources” are not hard-coded, so they can be used both during the development phase and the operational phase