Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to read text file from spring boot jar

Tags:

spring-boot

I am trying to read a file in the resources folder of my Spring boot console application but I am getting file not found exception.

here is my pom

<resource>
    <directory>src/main/resources</directory>
    <includes>
      <include>**/*.*</include>
    </includes>
  </resource>

And here is the exception:

java.io.FileNotFoundException: class path resource [9.txt] cannot be resolved to absolute file path because it does not reside in the file system: jar:file:/Users/abc/Documents/workspace-sts-3.8.4.RELEASE/xyz/target/xyz-0.0.1-SNAPSHOT.jar!/BOOT-INF/classes!/9.txt

I opened the xyz-0.0.1-SNAPSHOT.jar file and the 9.txt is in BOOT-INF/classes folder.

Thanks, -dj

like image 883
desi Joe Avatar asked Dec 03 '25 14:12

desi Joe


2 Answers

It's Spring Boot, let's use ClassPathResource

@Component
public class MyBean {
    @Value("9.txt")
    private ClassPathResource resource;

    @PostConstruct
    public void init() throws IOException {
        Files.lines(resource.getFile().toPath(), StandardCharsets.UTF_8)
            .forEach(System.out::println);
    }
}

UPDATED: Since ClassPathResource supports resolution as java.io.File if the class path resource resides in the file system, but not for resources in a JAR it's better to use this way

@Component
public class MyBean {
    @Value("9.txt")
    private ClassPathResource resource;

    @PostConstruct
    public void init() throws IOException {
        try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(resource.getInputStream(), StandardCharsets.UTF_8))) {
            bufferedReader.lines()
                .forEach(System.out::println);
        }        
    }
}
like image 125
Andriy Slobodyanyk Avatar answered Dec 06 '25 20:12

Andriy Slobodyanyk


this is working for me!

InputStream in = this.getClass().getResourceAsStream("/" + len + ".txt");

where as this didn't work

ClassPathResource resource = new ClassPathResource(len + ".txt"); 
File file = resource.getFile();
like image 38
desi Joe Avatar answered Dec 06 '25 20:12

desi Joe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!