Takkun
Takkun

Reputation: 6361

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?

Upvotes: 34

Views: 111440

Answers (4)

PhoneixS
PhoneixS

Reputation: 11016

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 java.io.File so you can also use:

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

Upvotes: 13

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 135992

Spring has org.springframework.core.io.Resource 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" />
    </bean>

and you get it in your bean as Resource:

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

output

D:\workspace1\spring\target\test-classes\test\test1.xml

Now you can use it in new FileReader(file)

Upvotes: 5

Jigar Joshi
Jigar Joshi

Reputation: 240860

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

go for

getClass().getResource("classpath:storedProcedures.sql")

Upvotes: 0

Tomasz Nurkiewicz
Tomasz Nurkiewicz

Reputation: 340708

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);

Upvotes: 43

Related Questions