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

TAGS