gpt4 book ai didi

java - 使用 Maven ClassLoader.getSystemClassLoader().getResource() 返回 null

转载 作者:行者123 更新时间:2023-12-02 13:31:01 26 4
gpt4 key购买 nike

我的项目目录结构(在 Eclipse 中):

MyProject/
src/main/Java
src/main/resources
stories
file.story

在主类中,我在下面的行中返回,通过 MAVEN 执行主类时返回 null

String folderName = "stories";
URL appURL = ClassLoader.getSystemClassLoader().getResource(folderName);

通过maven执行时,appURL返回NULL。

通过阅读 Stackoverflow 上的一篇文章,我了解到,我正在服务器上运行 Web 应用程序,但没有对服务器上资源的引用,因此我们需要在 POM.xml 文件中添加一些代码。我已在 POM.xml 文件中添加了以下代码,但仍然无法正常工作:(

<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
<includes>
<include>stories</include>
</includes>
</resource>

</resources>

寻求帮助。

最佳答案

有两种方法可以实现这一目标

Approach 1)

如果不在main方法内部URL url = getClass().getClassLoader().getResource("someresource.xxx");如果它在 main 内部,您需要创建类的对象,然后对其调用 getClass 。

Approach 2)

通过扩展 URLStreamHandler

import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLStreamHandler;

/** A {@link URLStreamHandler} that handles resources on the classpath. */
public class YourClass extends URLStreamHandler {
/** The classloader to find resources from. */
private final ClassLoader classLoader;

public YourClass() {
this.classLoader = getClass().getClassLoader();
}

public YourClass(ClassLoader classLoader) {
this.classLoader = classLoader;
}

@Override
protected URLConnection openConnection(URL u) throws IOException {
final URL resourceUrl = classLoader.getResource(u.getPath());
return resourceUrl.openConnection();
}
}

引用号:URL to load resources from the classpath in Java

关于java - 使用 Maven ClassLoader.getSystemClassLoader().getResource() 返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43177931/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com