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

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?


Are we talking about standard 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);

From an answer of @NimChimpsky in similar question:

Resource resource = new ClassPathResource("storedProcedures.sql");
InputStream resourceInputStream = resource.getInputStream();

Using ClassPathResource and interface Resource. And make sure you are adding the resources directory correctly (adding /src/main/resources/ into the classpath).

Note that Resource have a method to get a so you can also use:

Resource resource = new ClassPathResource("storedProcedures.sql");
FileReader fr = new FileReader(resource.getFile());

Spring has which is designed for such situations. From context.xml you can pass classpath to the bean

<bean class="test.Test1">
        <property name="path" value="classpath:/test/test1.xml" />

and you get it in your bean as Resource:

public void setPath(Resource path) throws IOException {
    File file = path.getFile();



Now you can use it in new FileReader(file)

looks like you have maven project and so resources are in classpath by

go for


Need Your Help

Spring MVC @RequestMapping Inheritance

java spring-mvc

Coming from Struts2 I'm used to declaring @Namespace annotation on super classes (or and inheriting classes would subsequently pick up on the value in the @Namespace annotation o...

Using AsParallel()/Parellel.ForEach() guidelines?

c# .net multithreading parallel-processing

Looking for a little advice on leveraging AsParallel() or Parallel.ForEach() to speed this up.