简体   繁体   English

在JAVA Jar中添加和使用文件,就像在文件夹中一样

[英]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. 我有一个JAVA项目,其中包含一些* .sql文件,如果没有数据库可用,则可以在部署时运行,但我可以运行一些将这些* .sql文件应用于数据库的类。 But I have to make JAVA Jar file out of it in order to deploy. 但是我必须用它制作JAVA Jar文件才能进行部署。 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. 我确实知道如何从jar运行任何类,但是如果我不想提取文件,那么如何在Jar中添加和访问我的* .sql。

The *sql files that I need is being used the following way: 我需要的* sql文件正在按以下方式使用:

mysql -uroot -ppassword < databaseStructure.sql

that creates me database. 创建我的数据库。 somehow I need access that file out of jar when necessary. 我需要在某种情况下以某种方式从jar中访问该文件。

You can get an InputStream from files in your classpath. 您可以从类路径中的文件获取InputStream。 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 请参阅关于主题的上一则SO文章: 将文件作为InputStream加载的不同方法

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

Example: 例:

You have a file insertSomething.sql in your jar. 您的jar中有一个文件insertSomething.sql。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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