简体   繁体   中英

How to read .sql files internally in Java jar?

I currently have a folder of schema files in SQL that get executed when the application is executed. This is what I use to read and execute these files:

private static String getSchemaFromFile(String filename) throws IOException {
    StringBuilder stringBuilder = new StringBuilder();
    BufferedReader bufferedReader = new BufferedReader(new FileReader("src/schema/" + filename + ".sql"));
    String queryString;

    .....
}

The problem I think is to do with the path of the schema folder. I tried looking at getResourceAsStream but I can't seem to get it working.

It works fine when I run from eclipse but when I compile it into a JAR it says file not found. How do I ensure the path is correct?

Something along these lines. BTW this will probably fail unless you are running your jar (executing it in eclipse probably won't work).

 BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream("src/schema/" + filename + ".sql"))); 

From eclipse it works because eclipse enable java code to search from src/schema/ directory.But when you are using jar it requires an absolute path.

I will suggest store the absolute path where you place your .sql file in a property file so that you can change whenever you need it.Suppose you from property file you have get the location absolutePath . Then you can do this -

BufferedReader bufferedReader = new BufferedReader(new FileReader(absolutePath + filename + ".sql"));

If the schema is in a jar file, then src/schema is probably not valid, more likely it will be in schema/. First you need to confirm this. The jar file is actually a zip file, so you can unzip it with utility like winzip to examine the contents.

Once confirmed where the schema files are located, they cannot be accessed using FileReader, as they are not in the file system but inside your jar. To access a file from within the jar file, getResourceAsStream is the correct approach. You probably defined the wrong folder when you tried it last time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM