3

In my SpringBoot project I would like to read an image file located in:

enter image description here

I tried:

URL url = getClass().getResource("android.png"); File f = new File(url.getPath()); 

and:

URL url = getClass().getResource("static/images/android.png"); File f = new File(url.getPath()); 

but the result is null.

EDIT: this worked

try { File file = new ClassPathResource("static/images/android.png").getFile(); } catch (IOException e) { } 
2
  • 1
    Try a leading slash /static/images/android.png" Commented Apr 13, 2017 at 8:33
  • try this.getClass().getClassLoader().getResource("static/images/android.png") Commented Apr 13, 2017 at 8:34

4 Answers 4

3

If you are using Spring, then it's better to use the built-in ClassPathResource class to access files within your classpath.

Sign up to request clarification or add additional context in comments.

Comments

2

You can try this

File file = new ClassPathResource("/images/android.png").getFile(); 

because we can access static folder from anywhere

Comments

1

you can use this.getClass().getResource("/static/images").getFile(); to get the folder location and then append with the file name to get the file location.

Example

String path=this.getClass().getResource("/static/images").getFile(); File File f = new File(path+"/​android.png"); 

Comments

0

Have you tried

ClassLoader.getSystemResourceAsStream("/static/images/android.png"); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.