3

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

desi Joe
  • 363
  • 5
  • 18

4 Answers4

7

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);
        }        
    }
}
Andriy Slobodyanyk
  • 1,965
  • 14
  • 15
  • I forgot to mention that I was using ClassPathResource. ClassPathResource resource = new ClassPathResource(len + ".txt"); File file = resource.getFile(); – desi Joe May 09 '17 at 17:25
2

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();
desi Joe
  • 363
  • 5
  • 18
1

In Spring Boot you can use ResourceLoader to read the file from Resource folder. It is an efficient way to read a file from the resource folder. First Autowire ResourceLoader

@Autowired
private ResourceLoader resourceLoader;

then

Resource resource = resourceLoader.getResource(CLASSPATH_URL_PREFIX + "9.txt");
InputStream inputStream = resource.getInputStream();
Filnor
  • 1,290
  • 2
  • 23
  • 28
Rajesh V
  • 11
  • 2
1

Use resource.getInputStream() instead of resource.getFile() when loading a file from inside a jar file.

Markus Pscheidt
  • 6,853
  • 5
  • 55
  • 76