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

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

问题描述

在使用 Maven 项目和 Jar 文件时,我在引用资源时遇到了一个令人讨厌的问题...

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

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

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")

这在 Eclipse 中工作正常,但在 Jar 文件中失败 - 资源位于 jar 根目录正下方的文件夹中...

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...

有谁知道在 Eclipse 中引用 JAR 和 (!) 中的文件的最佳实践"吗?

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

问题是,虽然资源实际上位于顶级文件夹资源"中的JAR中,但上述方法无法找到该文件...

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...

推荐答案

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

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.

我不明白您的场景中的问题是什么.通过 getClass().getResource("/filename.txt") 引用资源从类路径的根开始,无论那个(或其元素)是 target/classes 或 JAR 的根目录.我看到的唯一可能的错误是您使用了错误的 ClassLoader.

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.

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

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").

但除此之外:如果它不起作用,您可能在构建过程中的某个地方做错了.你能验证资源在 JAR 中吗?

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 和调试正确引用资源文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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