Source https://howtodoinjava.com/core-java/io/read-file-from-resources-folder/
Project Structure
Below image describe the folder structure used in this example.
Read file using ClassLoader.getResource().toURI()
In this example, we will use the ClassLoader
reference of instance of class.
package com.howtodoinjava.demo;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
public class ReadResourceFileDemo
{
public static void main(String[] args) throws IOException
{
String fileName = "config/sample.txt" ;
ClassLoader classLoader = new ReadResourceFileDemo().getClass().getClassLoader();
File file = new File(classLoader.getResource(fileName).getFile());
System.out.println( "File Found : " + file.exists());
String content = new String(Files.readAllBytes(file.toPath()));
System.out.println(content);
}
}
|
If you do not want to create any un-necessary instance of any class then you may utilize system classloader instance as below:
String fileName = "config/sample.txt" ;
// ClassLoader classloader = Thread.currentThread().getContextClassLoader();
ClassLoader classLoader = ClassLoader.getSystemClassLoader();
File file = new File(classLoader.getResource(fileName).getFile());
System.out.println( "File Found : " + file.exists());
String content = new String(Files.readAllBytes(file.toPath()));
System.out.println(content);
|
Program output is shown below.
Output:
File Found : true
Test Content
Read file using Spring’s ResourceUtils.getFile()
If your application happens to be spring based application then you may directly take advantage of ResourceUtils
class.
File file = ResourceUtils.getFile( "classpath:config/sample.txt" )
System.out.println( "File Found : " + file.exists());
String content = new String(Files.readAllBytes(file.toPath()));
System.out.println(content);
|
Program output is shown below.
Output:
File Found : true
Test Content
Happy Learning !!
References: