在使用Maven项目和Jar文件时,我有一个令人讨厌的问题引用资源...
我将所有资源都放在专用文件夹/ src/main/resources中,这是Eclipse中构建路径的一部分.使用引用文件
getClass().getResource("/filename.txt")
Run Code Online (Sandbox Code Playgroud)
这在Eclipse中运行良好但在Jar文件中失败 - 资源位于jar根目录正下方的文件夹中...
有没有人知道在JAR和Eclipse中的(!)引用文件的"最佳实践"?
编辑: 问题是,虽然资源实际上位于顶级文件夹"资源"中的JAR中,但上述方法无法找到文件...
Sea*_*oyd 19
Maven资源文件夹的内容被复制到目标/类,并从那里复制到生成的Jar文件的根目录.这是预期的行为.
我不明白的是你的场景中存在的问题.引用资源通过getClass().getResource("/filename.txt")
从类路径的根开始,无论是(或其元素)是target/classes
还是JAR的根.我看到的唯一可能的错误是你使用了错误ClassLoader
.
确保使用该资源的类与资源位于同一工件(JAR)中,并执行ThatClass.class.getResource("/path/with/slash")
或操作ThatClass.class.getClassLoader().getResource("path/without/slash")
.
但除此之外:如果它不起作用,你可能在构建过程中的某个地方做错了什么.你能验证资源是否在JAR中?
Tho*_*aux 19
打包JAR后,您的资源文件不再是文件,而是流,因此getResource
不起作用!
使用getResourceAsStream
.
要获取"文件"内容,请使用https://commons.apache.org/proper/commons-io/javadocs/api-release/org/apache/commons/io/IOUtils.html:
static public String getFile(String fileName)
{
//Get file from resources folder
ClassLoader classLoader = (new A_CLASS()).getClass().getClassLoader();
InputStream stream = classLoader.getResourceAsStream(fileName);
try
{
if (stream == null)
{
throw new Exception("Cannot find file " + fileName);
}
return IOUtils.toString(stream);
}
catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
return null;
}
Run Code Online (Sandbox Code Playgroud)
and*_*lko 18
我遇到了类似的问题.经过一整天的尝试每一个组合和调试后,我尝试了getClass().getResourceAsStream("resources/filename.txt")并最终使其工作.没有其他任何帮助.
归档时间: |
|
查看次数: |
68421 次 |
最近记录: |