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?
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.
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.
By default Spring Boot will serve static content from a directory called /static (or /public or /resources or /META-INF/resources) in the classpath.
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);
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());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With