Spring Boot - Reading Text File using ResourceLoader

I had the same problem and as @Gipple Lake explained, with Spring boot you need to load file as inputStream. So bellow I'll add my code as example, where I want to read import.xml file

public void init() {
    Resource resource = new ClassPathResource("imports/imports.xml");
    try {
        InputStream dbAsStream = resource.getInputStream();
        try {
            document = readXml(dbAsStream);
            } catch (SAXException e) {
                trace.error(e.getMessage(), e);
                e.printStackTrace();
            } catch (ParserConfigurationException e) {
                trace.error(e.getMessage(), e);
                e.printStackTrace();
            }
    } catch (IOException e) {
        trace.error(e.getMessage(), e);
        e.printStackTrace();
    }
    initListeImports();
    initNewImports();
}

public static Document readXml(InputStream is) throws SAXException, IOException,
      ParserConfigurationException {
      DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

      dbf.setValidating(false);
      dbf.setIgnoringComments(false);
      dbf.setIgnoringElementContentWhitespace(true);
      dbf.setNamespaceAware(true);
      DocumentBuilder db = null;
      db = dbf.newDocumentBuilder();

      return db.parse(is);
  }

I added "imports.xml" bellow src/main/ressources/imports


Put the files under resources/static, it will be in classpath and read the path like below

import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

Resource resource = new ClassPathResource("/static/pathtosomefile.txt");
resource.getURL().getPath()

I have checked your code.If you would like to load a file from classpath in a Spring Boot JAR, then you have to use the resource.getInputStream() rather than resource.getFile().If you try to use resource.getFile() you will receive an error, because Spring tries to access a file system path, but it can not access a path in your JAR.

detail as below:

https://smarterco.de/java-load-file-classpath-spring-boot/


Please try resourceLoader.getResource("classpath:static/Sample.txt");

Working with this code when run with java -jar XXXX.jar

enter image description here

------ update ------

After go through your codes, the problem is you try to read the file by the FileInputStream but actually it's inside the jar file.

But actually you get the org.springframework.core.io.Resource so means you cat get the InputStream, so you can do it like new BufferedReader(new InputStreamReader(resource.getInputStream())).readLine();