有没有办法将csv / json文件从外部加载到jar中?

时间:2018-12-19 04:27:41

标签: java spring spring-boot

我正在尝试从外部将json文件加载到jar文件中。这是一个小的spring boot应用程序。这个json文件一直在变化,因此我不想将其捆绑在jar中,而是希望将其保留在外部,以便每次更改此文件时都无需构建jar。 现在,我的Java jar命令如下:java -jar build/libs/my-customer-service.jar --app.build.number=1234 -Dloader.path=./config/PotentialCustomers.json --spring.config.location=./src/main/resources/my-customer-service-application.properties 而且我正在访问该文件,如下所示:

@PostConstruct
public void init() {
    try (InputStream iStream = new ClassPathResource("PotentialCustomers.json").getURL().openStream()) {
        ObjectMapper am = new ObjectMapper();
        Map<String,String> customerMap = am.readValue(iStream, new TypeReference<Map<String, String>>() {
        });
       } catch (IOException e) {
        e.printStackTrace();    }
}

我遇到此异常:

java.io.FileNotFoundException: class path resource [PotentialCustomers.json] cannot be resolved to URL because it does not exist
at org.springframework.core.io.ClassPathResource.getURL(ClassPathResource.java:195)
at com.jetblue.jbms.api.util.PhoneNumBlackListChecker.init(PhoneNumBlackListChecker.java:24)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor$LifecycleElement.invoke(InitDestroyAnnotationBeanPostProcessor.java:366)

1 个答案:

答案 0 :(得分:1)

首先,请确保您已准备好像这样的文件夹结构。

./ - the root of your program
 |__ your_jar_file.jar
 |__ some_properties_file.properties

要从jar内的代码访问some_properties_file.properties,请使用下面的实用程序功能。

Properties appProperties = new Properties();
FileInputStream file;

String path = "./some_properties_file.properties";    
file = new FileInputStream(path);

appProperties .load(file);
String propValue= appProperties .getProperty("Property_Name");