简体   繁体   中英

Add and use files in JAVA Jar as they would be in the folder

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.

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

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");

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