与maven的Java项目无法找到资源

问题描述 投票:0回答:1

我目前正在尝试从资源文件夹中获取文件(index.html),但它始终返回null。

加载文件的代码:

ClassLoader loader = this.getClass().getClassLoader();

    File file = null;
    try {
        System.out.println(loader.getResource("/public/index.html") + "is the resource");
    } catch (Exception e) {
        e.printStackTrace();
    }

这些文件位于资源文件夹Resource folder with files

jar file with folder

这是包含文件夹的.jar文件。看到图片顶部的网址)

我有默认的pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>it.bachmann</groupId>
    <artifactId>servertracker</artifactId>
    <version>1.0</version>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
    <dependencies>
        <dependency>
            <groupId>com.parse.bolts</groupId>
            <artifactId>bolts-tasks</artifactId>
            <version>1.4.0</version>
        </dependency>
        <dependency>
            <groupId>io.javalin</groupId>
            <artifactId>javalin</artifactId>
            <version>1.2.0</version>
        </dependency>
        <dependency>
            <groupId>org.json</groupId>
            <artifactId>json</artifactId>
            <version>20160810</version>
        </dependency>
        <dependency>
            <groupId>com.auth0</groupId>
            <artifactId>java-jwt</artifactId>
            <version>3.3.0</version>
        </dependency>
    </dependencies>
</project>
java maven nullpointerexception
1个回答
0
投票

我认为您的观察是在测试问题中所述的代码时发生的。

如果是这样,这里的问题可能是您尝试加载的资源实际上是在src/main/resources中。

解决方案:尝试将index.html移动到src/test/resources。不要忘记将目录标记为测试资源根目录(如果正确完成,您的模块设置应该看起来像this

© www.soinside.com 2019 - 2024. All rights reserved.