如何访问JAR文件中的Maven资源? [英] How to access Maven resources in JAR file?
问题描述
我有一个用Maven构建的Java应用程序.我有一个资源文件夹com/pkg/resources/...
,我需要从中访问文件.例如directory.txt
.我一直在看各种教程和其他SO答案,但似乎没有一个适合我.现在我有:
I have a Java application that I build with Maven. I have a resources folder com/pkg/resources/...
that I need to access files from. For example directory.txt
. I've been looking at various tutorials and other SO answers, but none seem to work for me. Right now I have:
ClassLoader classLoader = getClass.getClassLoader();
File file = new File(classLoader.getResource("/directory.txt");
当我输出f.length
时,我得到0字节的结果.我也尝试过:
When I output f.length
I get a result of 0 bytes. I've also tried:
InputStream is = (this.getClass().getClassLoader().getResourceAsStream("/directory.txt"));
try{
File file = File.createTempFile("dir", ".txt");
Files.copy(is, file.toPath());
} catch (IOException e) {
e.printStackTrace();
}
但是该代码也不起作用.我以前从未使用过从JAR访问文件.关于可能出什么问题的任何想法?
But that code does not work either. I haven't worked with accessing files from a JAR before. Any ideas on what might be going wrong?
推荐答案
首先,使用"src/main/resources"文件夹,例如在资源中,您可以拥有一个名为dummy.txt的文件
First, use the "src/main/resources" folder, for example in resources you can have a file named: dummy.txt
完整路径应为:src/main/resources/dummy.txt
Full path should be: src/main/resources/dummy.txt
在某些课程中,您可以按照以下方式读取dummy.txt:
In some class you could read dummy.txt as folow:
String dummy = new String(IOUtils.toByteArray(this.getClass().getClassLoader().getResourceAsStream("/dummy.txt")));
此外,如果您想在其中放置文件夹,也可以使用它.例如:
Also, if you want to have folders in there you can have it. For example:
src/main/resources/com/pkg/resources/dummy.txt
src/main/resources/com/pkg/resources/dummy.txt
String dummy = new String(IOUtils.toByteArray(this.getClass().getClassLoader().getResourceAsStream("/com/pkg/resources/dummy.txt")));
请考虑在此示例中,我们对pom.xml中的类路径信息没有做任何事情
Have as consideration that in this example we are not doing nothing with the classpath information in our pom.xml
注意:IOUtils来自commons-io,例如:
Note: IOUtils is from commons-io , for example:
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
这篇关于如何访问JAR文件中的Maven资源?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!