2

I have few files with SQL queries in my Spring Boot project. These queries are located by path

spring-boot-sql-in-files/src/main/resources/sql/query.sql 

When I run my application I execute loading of these queries to static variables.

private static final String PATH_PREFIX = "src/main/resources/sql/"; public static String loadQueryFromFile(@NonNull String fileName) { try { return FileUtils.readFileToString(new File(PATH_PREFIX + fileName), Charset.defaultCharset()); } catch (Exception e) { log.error("Error occurred during loading sql file to string, file=" + fileName, e); throw new QueryNotLoadedException(); } } 

It works fine when I run it using IDE but it doesn't work when I run name.jar file, I get the following error:

java.io.FileNotFoundException: File 'src/main/resources/sql/query.sql' does not exist 

How can I fix this path?

6
  • 1
    Have you verified that the files are present in the jar file? Commented Oct 11, 2017 at 13:11
  • 2
    Ofcourse it won't run... src/main/resources is the root of your classpath. Which will also make that FileUtils.readFileToString won't work as it isn't a File when packaged as a jar. Instead use the Spring resource abstraction and utils to load it into a string. Commented Oct 11, 2017 at 13:12
  • @neuhaus, I have verified, it folder is located /BOOT-INF/classes/sql/ Commented Oct 11, 2017 at 13:12
  • Use @Value(value = "classpath: sql/query.sql") private Resource companiesXml; then use the below code in your method to get a stream and companiesXml.getInputStream() ...Let me if it helps Commented Oct 11, 2017 at 13:14
  • try with new ClassPathResource("/sql/query.sql").getFile(); to get the file. Commented Oct 11, 2017 at 13:15

1 Answer 1

8

src/main/resources like src/main/java becomes the root of your classpath and as such won't work. It won't work with only sql as well as it isn't a file when packaged as a jar. Instead use the Spring Resource abstraction to load the file and the StreamUtils to load it into a String.

public static String loadQueryFromFile(@NonNull String fileName) { try { Resource resource = new ClassPathResource("sql/" + fileName); return StreamUtils.copyToString(resource.getInputStream(), Charset.defaultCharset()); } catch (Exception e) { log.error("Error occurred during loading sql file to string, file=" + fileName, e); throw new QueryNotLoadedException(); } } 

Something like that should do the trick.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.