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
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);
}
}
}
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With