如何使用 Java 类加载器从类路径加载文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1094786/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 23:37:59  来源:igfitidea点击:

How do I use the Java ClassLoader to load a file fromthe classpath?

javapropertiesclassloader

提问by Kyle Boon

I want to use the ClassLoader to load a properties file for the Properties class. I've simplified the below code to remove error handling for the purposes of this discussion:

我想使用 ClassLoader 加载 Properties 类的属性文件。出于本次讨论的目的,我简化了以下代码以删除错误处理:

loader = this.getClass().getClassLoader();
in = loader.getResourceAsStream("theta.properties");
result = new Properties();
result.load(in);

In the same directory as this class I have the file "theta.properties" but the InputStream is always null. Am I putting the file in the wrong place? I'm using eclipse and its set to build the class files to the source folder - so that shouldn't be the problem.

在与此类相同的目录中,我有文件“theta.properties”,但 InputStream 始终为空。我是否将文件放在错误的位置?我正在使用 eclipse 及其设置将类文件构建到源文件夹 - 所以这应该不是问题。

I can't find anything in the JavaDoc to get the ClassLoader to tell me what classpath is being searched.

我在 JavaDoc 中找不到任何内容来让 ClassLoader 告诉我正在搜索什么类路径。

采纳答案by Kathy Van Stone

By using getClass().getClassloader()you look for "theta.properties" from the root path directory. Just use getClass().getResourceAsStream()to get a resource relative to that class.

通过使用,getClass().getClassloader()您可以从根路径目录中查找“theta.properties”。仅用于getClass().getResourceAsStream()获取与该类相关的资源。

回答by Yishai

If the file is in the same directory as the class, you have to prefix the class's package as a directory.

如果文件与类位于同一目录中,则必须将类的包作为目录作为前缀。

So if your package is:

所以如果你的包裹是:

package com.foo.bar;

Then your code is:

那么你的代码是:

.getResourceAsStream("com/foo/bar/theta.properties");

回答by Kathy Van Stone

You can use ResourceBundle

您可以使用 ResourceBundle