9 Proven Ways to Read Files from the resources Folder in Spring Boot

This guide details nine practical techniques for accessing files in a Java project's resources folder, covering classloader paths, URL decoding, getFile vs getPath, InputStream retrieval, ClassPathResource usage, absolute paths, and environment variable methods, with complete code examples for each approach.

Programmer DD
Programmer DD
Programmer DD
9 Proven Ways to Read Files from the resources Folder in Spring Boot

This article presents nine methods to read files located in the resources directory of a Java project, especially when using Spring Boot.

/**
 * 根据文件路径读取文件内容
 *
 * @param fileInPath
 * @throws IOException
 */
public static void getFileContent(Object fileInPath) throws IOException {
    BufferedReader br = null;
    if (fileInPath == null) {
        return;
    }
    if (fileInPath instanceof String) {
        br = new BufferedReader(new FileReader(new File((String) fileInPath)));
    } else if (fileInPath instanceof InputStream) {
        br = new BufferedReader(new InputStreamReader((InputStream) fileInPath));
    }
    String line;
    while ((line = br.readLine()) != null) {
        System.out.println(line);
    }
    br.close();
}

Method 1

The core approach uses getResource("") and getPath() to obtain the directory path.

public void function1(String fileName) throws IOException {
    String path = this.getClass().getClassLoader().getResource("").getPath(); // getResource("") is empty
    System.out.println(path);
    String filePath = path + fileName;
    System.out.println(filePath);
    getFileContent(filePath);
}

Method 2

This method directly calls getResource(fileName) to get the path and decodes it when the path contains Chinese characters.

/**
 * 直接通过文件名getPath来获取路径
 *
 * @param fileName
 * @throws IOException
 */
public void function2(String fileName) throws IOException {
    String path = this.getClass().getClassLoader().getResource(fileName).getPath();
    System.out.println(path);
    String filePath = URLDecoder.decode(path, "UTF-8"); // decode if Chinese characters are present
    System.out.println(filePath);
    getFileContent(filePath);
}

Method 3

Uses getFile() on the URL; getFile() includes query parameters while getPath() does not.

url.getFile() = /pub/files/foobar.txt?id=123456
url.getPath() = /pub/files/foobar.txt

Code example:

/**
 * 直接通过文件名+getFile()来获取
 *
 * @param fileName
 * @throws IOException
 */
public void function3(String fileName) throws IOException {
    String path = this.getClass().getClassLoader().getResource(fileName).getFile();
    System.out.println(path);
    String filePath = URLDecoder.decode(path, "UTF-8");
    System.out.println(filePath);
    getFileContent(filePath);
}

Method 4 (Important)

Uses getResourceAsStream to obtain an InputStream, which works inside a Spring Boot jar where no real file path exists.

/**
 * 直接使用getResourceAsStream方法获取流
 * springboot项目中需要使用此种方法,因为jar包中没有一个实际的路径存放文件
 *
 * @param fileName
 * @throws IOException
 */
public void function4(String fileName) throws IOException {
    InputStream in = this.getClass().getClassLoader().getResourceAsStream(fileName);
    getFileContent(in);
}

Method 5 (Important)

Also uses getResourceAsStream but without the class loader, accessing the file from the root of resources with a leading slash.

/**
 * 直接使用getResourceAsStream方法获取流
 * 如果不使用getClassLoader,可以使用getResourceAsStream("/配置测试.txt")直接从resources根路径下获取
 *
 * @param fileName
 * @throws IOException
 */
public void function5(String fileName) throws IOException {
    InputStream in = this.getClass().getResourceAsStream("/" + fileName);
    getFileContent(in);
}

Method 6 (Important)

Uses Spring's ClassPathResource to obtain an InputStream, recommended for Spring Boot projects.

/**
 * 通过ClassPathResource类获取,建议SpringBoot中使用
 * springboot项目中需要使用此种方法,因为jar包中没有一个实际的路径存放文件
 *
 * @param fileName
 * @throws IOException
 */
public void function6(String fileName) throws IOException {
    ClassPathResource classPathResource = new ClassPathResource(fileName);
    InputStream inputStream = classPathResource.getInputStream();
    getFileContent(inputStream);
}

Method 7

Retrieves the file using an absolute local path; not suitable for server environments.

/**
 * 通过绝对路径获取项目中文件的位置(不能用于服务器)
 * @param fileName
 * @throws IOException
 */
public void function7(String fileName) throws IOException {
    String rootPath = System.getProperty("user.dir"); // e.g., E:\WorkSpace\Git\spring-framework-learning-example
    String filePath = rootPath + "\\chapter-2-springmvc-quickstart\\src\\main\\resources\\" + fileName;
    getFileContent(filePath);
}

Method 8

Uses new File("") to get the current directory's absolute path; also only works locally.

/**
 * 通过绝对路径获取项目中文件的位置(不能用于服务器)
 * @param fileName
 * @throws IOException
 */
public void function8(String fileName) throws IOException {
    // 参数为空
    File directory = new File("");
    // 规范路径:getCanonicalPath() 方法返回绝对路径,会把 ..\ 、.\ 这样的符号解析掉
    String rootCanonicalPath = directory.getCanonicalPath();
    // 绝对路径:getAbsolutePath() 方法返回文件的绝对路径
    String rootAbsolutePath = directory.getAbsolutePath();
    System.out.println(rootCanonicalPath);
    System.out.println(rootAbsolutePath);
    String filePath = rootCanonicalPath + "\\chapter-2-springmvc-quickstart\\src\\main\\resources\\" + fileName;
    getFileContent(filePath);
}

Method 9

Sets an environment variable (e.g., TEST_ROOT) and builds the file path from it.

/**
 * 通过绝对路径获取项目中文件的位置
 *
 * @param fileName
 * @throws IOException
 */
public void function9(String fileName) throws IOException {
    System.setProperty("TEST_ROOT", "E:\\WorkSpace\\Git\\spring-framework-learning-example");
    // 参数为空
    String rootPath = System.getProperty("TEST_ROOT");
    System.out.println(rootPath);
    String filePath = rootPath + "\\chapter-2-springmvc-quickstart\\src\\main\\resources\\" + fileName;
    getFileContent(filePath);
}
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaBackend DevelopmentSpring BootResourcesfile I/O
Programmer DD
Written by

Programmer DD

A tinkering programmer and author of "Spring Cloud Microservices in Action"

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.