Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

read file in classpath

Here is what I want to do and I am wondering if there is any Spring classes that will help with implementing. I don't have to use spring for this particular problem, I'm just implementing it with everything else.

In my DAO layer I want to externalize my sql files aka 1 sql per file. I want to read and cache the sql statement even maybe as a spring bean singleton. But in my initial struggles, I am having a problem just loading a sql file in the classpath...

Is there anything in spring to help with that? I've been through the documentation but nothing is jumping out at me.

Here is kind of what I'm after.. but I can't get it to recognize the file or maybe the classpath... not real sure does something need to be defined in applicationContext?

Here are a couple of attempts that do not seem to work... both spring'ish and just java'ish.

reader = new BufferedReader(new InputStreamReader(new ClassPathResource("com.company.app.dao.sql.SqlQueryFile.sql").getInputStream())  reader = new BufferedReader(new InputStreamReader(ClassLoader.getSystemResourceAsStream("com.company.app.dao.sql.SqlQueryFile.sql"))); 

Any thoughts?

like image 522
Greg J Avatar asked Apr 09 '09 15:04

Greg J


People also ask

What is classpath file in Java?

classpath maintains the project's source and target references for Java compilation and compressed file or project dependencies. This configuration is maintained through the Java Build Path page in the project's properties.

How do you load a file in Java?

Example 1: Java Program to Load a Text File as InputStream txt. Here, we used the FileInputStream class to load the input. txt file as input stream. We then used the read() method to read all the data from the file.


1 Answers

Change . to / as the path separator and use getResourceAsStream:

reader = new BufferedReader(new InputStreamReader(     getClass().getClassLoader().getResourceAsStream(         "com/company/app/dao/sql/SqlQueryFile.sql"))); 

or

reader = new BufferedReader(new InputStreamReader(     getClass().getResourceAsStream(         "/com/company/app/dao/sql/SqlQueryFile.sql"))); 

Note the leading slash when using Class.getResourceAsStream() vs ClassLoader.getResourceAsStream. getSystemResourceAsStream uses the system classloader which isn't what you want.

I suspect that using slashes instead of dots would work for ClassPathResource too.

like image 185
Jon Skeet Avatar answered Sep 18 '22 21:09

Jon Skeet