Question

I have JAVA project which contains some *.sql files and on deploy if there is no database cleated yet I can run some classes which applies those *.sql files on database. But I have to make JAVA Jar file out of it in order to deploy. I do know how to run any class from jar, but how to add and access my *.sql in the Jar if I do not want extract the files.

The *sql files that I need is being used the following way:

mysql -uroot -ppassword < databaseStructure.sql

that creates me database. somehow I need access that file out of jar when necessary.

Was it helpful?

Solution

InputStream stream = YourClass.class.getResourceAsStream("/" + pathToYourFile);

Example:

You have a file insertSomething.sql in your jar.

public static String getResourceContent(
  final String path) throws IOException {
        InputStream stream = YourClass.class.getResourceAsStream("/" + path);
        if (stream != null) {
               return IOUtils.toString(stream);
        } 
    }

Now you can get the content:

String content = getResourceContent("insertSomething.sql");

OTHER TIPS

You can get an InputStream from files in your classpath. I'm not sure if that does what you need, exactly.

See this previous SO article on the topic: Different ways of loading a file as an InputStream

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top