获取 Maven 项目中 resources 目录的绝对地址

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.

  1. Obtained through the relative directory and the File API

The code is as follows:

1
2
String path = "src/main/resources/templates";
File folder = new File(path);
  1. Obtained through relative directories and the Path API after Java 7
1
2
Path templateFolder = Paths.get("src", "main", "resources", "templates");
templateFolder.toFile()
  1. 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
2
3
String resouceName = "logback.xml";
ClassLoader classLoader = getClass().getClassLoader();
File file = new File(classLoader.getResource(resouceName).getFile());

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

本文标题:获取 Maven 项目中 resources 目录的绝对地址

文章作者:Morning Star

发布时间:2021年06月17日 - 11:06

最后更新:2022年01月08日 - 12:01

原始链接:https://www.mls-tech.info/java/java-get-resource-path-en/

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。