从可执行文件.jar运行时无法读取xml

时间:2019-10-31 15:56:57

标签: java maven spring-boot

我将一些设置保存在我的资源文件夹的xml索引中。一切正常,直到我尝试在无法过滤的可执行.jar文件中运行软件为止。

我在pom.xml中添加了资源,如果检查.jar文件,我可以在classes文件夹中看到.xml。 当我调试.jar文件时,在文档doc = dBuilder.parse(xml)上得到了一个例外,它找不到该文件:

java.io.FileNotFoundException:C:\ Users \ dante \ IdeaProjects \ BACbrowser \ file:\ C:\ Users \ dante \ IdeaProjects \ BACbrowser \ backend \ target \ backend-0.0.1-SNAPSHOT.jar!\ BOOT -INF \ classes!\ defaultSettings(Date语法,Datenamen,Verzeichnisnamen或Datenträgerbezeichnung和falsch)

public void readXMLSettings() {
    try {

        File xml = getXmlSettingsFile();
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        Document doc = dBuilder.parse(xml);

        setPort((doc.getElementsByTagName("port").item(0).getTextContent()));
        setSiteName(doc.getElementsByTagName("siteName").item(0).getTextContent());
        setSiteDescription(doc.getElementsByTagName("siteDescription").item(0).getTextContent());
        setBacnetSeparator(doc.getElementsByTagName("bacnetSeparator").item(0).getTextContent());

    } catch (Exception e) {
        System.err.println("Can't read XML settings");
        ;
    }
}

private File getXmlSettingsFile() {
    ClassLoader classLoader = getClass().getClassLoader();
    URL resource = classLoader.getResource("defaultSettings");
    if (resource == null) {
        throw new IllegalArgumentException("file is not found!");
    } else {
        return new File(resource.getFile());
    }

}

1 个答案:

答案 0 :(得分:0)

使用Spring Boot中的application.properties并直接保存那里的设置就可以了!

spring.boot.config.settings.port = BAC0
spring.boot.config.settings.siteName = Anlage
spring.boot.config.settings.siteDescription = Site
spring.boot.config.settings.bacnetSeparator = '

通过在班级上添加@ConfigurationProperties(prefix = "spring.boot.config.settings")前缀,我可以毫无问题地访问它们。

private String port;
private String siteName;
private String siteDescription;
private String bacnetSeparator;

public String getPort() {
    return port;
}

public void setPort(String port) {
    this.port = port;
}

public String getSiteName() {
    return siteName;
}

public void setSiteName(String siteName) {
    this.siteName = siteName;
}

public String getSiteDescription() {
    return siteDescription;
}

public void setSiteDescription(String siteDescription) {
    this.siteDescription = siteDescription;
}

public String getBacnetSeparator() {
    return bacnetSeparator;
}

public void setBacnetSeparator(String bacnetSeparator) {
    this.bacnetSeparator = bacnetSeparator;
}