1

All I want to do is access a specific file in a Java class. I am using Spring Boot 2.0.0.M7. When I run from my development machine using mvn spring-boot:run then everything works well. In that case I am using:

File jFile = new File("src/main/resources/static/folder/fileName.txt");

When I deploy this to a Tomcat server (8.5) as a war, the file is put into:

WEB-INF/classes/static/folder/fileName.txt

I've tried everything I could find or think of, but always get an error of some sort, usually a file not found exception.

My most recent attempt was:

URL url = this.getClass().getClassLoader().getResource("fileName.txt");
File jFile = new File(url.getPath());

That produces a null pointer exception with url.getPath().

I have read about needing to access the servlet config, but couldn't ever understand that well enough to get it to work. Does anyone have a clear example so that I can access the file both from the development context and the production context? Thanks!

Tim
  • 1,605
  • 6
  • 31
  • 47
  • Try this File file = new ClassPathResource("filename.txtl").getFile(); – Anunay Feb 03 '18 at 05:51
  • @Anunay I had tried that at one point earlier. It doesn't work like that, but it does work if I use `ClassPathResource("static/folder/filename.txt")` which I only discovered by trial and error. Can you explain why I need to start with `static` when most resources say that Spring will find the resource if it is in the class path? Am I missing some sort of needed configuration? – Tim Feb 05 '18 at 17:11

0 Answers0