Project Structure
Read file using ClassLoader.getResource().toURI()
In this example, we will use the 
ClassLoader reference of instance of class.| packagecom.howtodoinjava.demo;importjava.io.File;importjava.io.IOException;importjava.nio.file.Files;publicclassReadResourceFileDemo{    publicstaticvoidmain(String[] args) throwsIOException    {        String fileName = "config/sample.txt";        ClassLoader classLoader = newReadResourceFileDemo().getClass().getClassLoader();        File file = newFile(classLoader.getResource(fileName).getFile());                //File is found        System.out.println("File Found : "+ file.exists());                //Read File Content        String content = newString(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 = newFile(classLoader.getResource(fileName).getFile());//File is foundSystem.out.println("File Found : "+ file.exists());//Read File ContentString content = newString(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")//File is foundSystem.out.println("File Found : "+ file.exists());//Read File ContentString content = newString(Files.readAllBytes(file.toPath()));System.out.println(content); | 
Program output is shown below.
Output: File Found : true Test Content
Happy Learning !!
References:

 
Không có nhận xét nào:
Đăng nhận xét