Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 201
Takkun Avatar asked Nov 26 '12 19:11

Takkun


People also ask

How do you specify file path in application properties in spring boot?

Spring Boot loads the application. properties file automatically from the project classpath. All you have to do is to create a new file under the src/main/resources directory.

How do I load a file in classpath?

We can either load the file(present in resources folder) as inputstream or URL format and then perform operations on them. So basically two methods named: getResource() and getResourceAsStream() are used to load the resources from the classpath. These methods generally return the URL's and input streams respectively.

What is classpath location in spring boot?

By default Spring Boot will serve static content from a directory called /static (or /public or /resources or /META-INF/resources) in the classpath.


2 Answers

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); 
like image 147
Tomasz Nurkiewicz Avatar answered Sep 28 '22 05:09

Tomasz Nurkiewicz


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()); 
like image 39
PhoneixS Avatar answered Sep 28 '22 03:09

PhoneixS