如何正确引用JAR和Debugging的资源文件? [英] How to reference a resource file correctly for JAR and Debugging?

查看:82
本文介绍了如何正确引用JAR和Debugging的资源文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Maven项目和Jar文件时引用了一个讨厌的问题。



我把所有的资源都放在一个专用的文件夹/ src / main /资源是Eclipse中构建路径的一部分。文件使用

  getClass()。getResource(/ filename.txt)

这在Eclipse中工作正常,但在Jar文件中失败 - 资源位于jar根目录下的文件夹中... <有没有人知道在Eclipse中引用JAR和(!)文件的最佳实践?



编辑:
问题是当资源实际位于JAR中的文件夹资源在顶层时,上述方法找不到文件...

解决方案

Maven资源文件夹的内容被复制到目标/类,并从那里复制到生成的Jar文件的根目录。这是预期的行为。



我不明白的是你的情况是什么问题。通过 getClass()引用资源getResource(/ filename.txt)从类路径的根部开始,无论(或其元素)是否为code> target / classes 或JAR的根目录。我看到的唯一可能的错误是您使用错误的 ClassLoader



确保使用的类资源与资源在同一个工件(JAR)中,并执行 ThatClass.class.getResource(/ path / with / slash) ThatClass.class.getClassLoader()。getResource(path / without / slash)



但除此之外:在工作中,您可能在构建过程中的某处发生错误。你可以验证资源是否在JAR中?


I have a nasty problem referencing resources when using a Maven project and Jar files...

I have all my resources in a dedicated folder /src/main/resources which is part of the build path in Eclipse. Files are referenced using

getClass().getResource("/filename.txt")

This works fine in Eclipse but fails in the Jar file - there the resources are located in a folder directly below the jar's root...

Does anyone know a 'best practice' to reference a file both in the JAR and (!) in Eclipse?

Edit: The problem is that while the resources actually are located in the JAR in a folder "resources" at the top level, the above method fails to find the file...

解决方案

The contents of Maven resource folders are copied to target/classes and from there to the root of the resulting Jar file. That is the expected behaviour.

What I don't understand is what the problem is in your scenario. Referencing a Resource through getClass().getResource("/filename.txt") starts at the root of the classpath, whether that (or an element of it) is target/classes or the JAR's root. The only possible error I see is that you are using the wrong ClassLoader.

Make sure that the class that uses the resource is in the same artifact (JAR) as the resource and do ThatClass.class.getResource("/path/with/slash") or ThatClass.class.getClassLoader().getResource("path/without/slash").

But apart from that: if it isn't working, you are probably doing something wrong somewhere in the build process. Can you verify that the resource is in the JAR?

这篇关于如何正确引用JAR和Debugging的资源文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆