英文:
How to specify resource location in the same way when compiling TO and NOT TO a JAR file
问题
我有一个正在使用 javac
编译的项目。我希望能够在不首先将我的项目构建为 JAR 文件的情况下获取资源,但与此同时,我也不想硬编码资源的位置(C://Users/name/etc)。
我知道如果我有一个 JAR 文件,我可以使用 ClassLoader
并从中调用其中的一个资源方法。或者,如果我的资源包含在另一个 JAR 文件中,并且该 JAR 文件位于我的类路径上,那么我可以以类似的格式从该 JAR 文件中提取它。
但是当我只使用 javac 编译时,我该如何做呢?我不想在最终将其制作成 JAR 文件时不得不重新调整所有我的资源获取逻辑,但我也不想每次编译并想要测试更改时都必须制作一个 JAR 文件。我只想能够告诉 Java 这是在哪里找到我的资源,而当我最终决定制作一个 JAR 文件时,我不想改变这个策略。
英文:
I have a project that I am compiling using javac
. I want to be able to fetch resources without having to first build my project into a JAR file, but at the same time, I don't want to hard code the location either (C://Users/name/etc).
I know that if I had a JAR file, I could use a ClassLoader
and call one of the resource methods from there. Alternatively, if my resources were contained within another JAR file, and that JAR file was on my class path, then I could fetch it from the JAR file in a similar format.
But how do I do so when I am only compiling in javac? I don't want to have to rework all of my resource fetching logic when I eventually turn this into a JAR file, but I also don't want to have to make a jar file every time I compile and want to test a change. I just want to be able to specify to Java that this is where to find my resources, and I don't want to change that strategy when I finally decide to making a JAR file.
答案1
得分: 1
你可以像在jar文件中一样在文件夹中找到资源。只需确保在运行java时通过 -cp
列出包含资源的文件夹,并且你的代码中的相对路径与之对应。
以下是一个示例。
java -cp ".;first/path/to/resource/folder;second/path;third/path" PackageName.NameOfClassContainingMainMethod
也就是说,资源可能位于与编译后的代码相同的文件夹中。在这种情况下,无需通过 -cp
显式提供它。
无论何时在你的代码中使用 ClassLoader.getResource
/ getResourceAsStream
加载资源,Java都会在类路径中查找它。提供 .jar(本质上只是一个压缩的文件夹)和原始文件夹只是指定要加载到类路径中的内容的替代方式。
英文:
You can locate resources in the folder same way as in a jar. Just make sure your folder with resources is listed via -cp
when running java and relative paths in your code corresponds to it.
Here is an example.
java -cp ".;first/path/to/resource/folder;second/path;third/path" PackageName.NameOfClassContainingMainMethod
That said, the resource might be inside of the same folder that your compiled code is in. In that case, there is no need to provide it explicitly via -cp
.
Whenever you are loading a resource in your code by ClassLoader.getResource
/ getResourceAsStream
java looks for it in the classpath. Providing .jar (which is essentially just a zipped folder) and raw folder is just an alternative ways to specify a content to be loaded into classpath.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论