Java Spring - How to use classpath to specify a file location?

Takkun picture Takkun · Nov 26, 2012 · Viewed 101.8k times · Source

How can I use the classpath to specify the location of a file that is within my Spring project?

This is what I have currently:

FileReader fr = new FileReader("C:\\Users\\Corey\\Desktop\\storedProcedures.sql");

This is hardcoded to my Desktop. What I would like is to be able to use the path to the file that is in my project.

FileReader fr = new FileReader("/src/main/resources/storedProcedures.sql");

Any suggestions?

Answer

Tomasz Nurkiewicz picture Tomasz Nurkiewicz · Nov 26, 2012

Are we talking about standard java.io.FileReader? Won't work, but it's not hard without it.

/src/main/resources maven directory contents are placed in the root of your CLASSPATH, so you can simply retrieve it using:

InputStream is = getClass().getResourceAsStream("/storedProcedures.sql");

If the result is not null (resource not found), feel free to wrap it in a reader:

Reader reader = new InputStreamReader(is);