https://www.mkyong.com/java/java-read-a-file-from-resources-folder/
this tutorial, we will show you how to read a file from a resources folder, in both Java and Unit Test environment. In simple, put files in a resources folder, and read the file with following code snippets :
ClassLoader classLoader = getClass().getClassLoader();
File file = new File(classLoader.getResource("file/test.xml").getFile());
1. Project Directory
Example to read a file “test.txt” from a
resources
folder.
main/resources/file/test.txt
This is line 1
This is line 2
This is line 3
This is line 4
This is line 5
Hello.java
package com.mkyong;
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class Hello {
public static void main(String[] args) {
Hello obj = new Hello();
System.out.println(obj.getFile("file/test.txt"));
}
private String getFile(String fileName) {
StringBuilder result = new StringBuilder("");
//Get file from resources folder
ClassLoader classLoader = getClass().getClassLoader();
File file = new File(classLoader.getResource(fileName).getFile());
try (Scanner scanner = new Scanner(file)) {
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
result.append(line).append("\n");
}
scanner.close();
} catch (IOException e) {
e.printStackTrace();
}
return result.toString();
}
}
Output
This is line 1
This is line 2
This is line 3
This is line 4
This is line 5