java 获取特定包内的文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1939629/
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-10-29 18:37:41  来源:igfitidea点击:

Get a file inside a specific package

javaclasspackage

提问by Lorenzo B

I've a java package (package A) and I would retrieve a file contained into another package (package B). For example, suppose that into package A I have a class named ClassA. The ClassA needs to access an xml file (i.e. a configuration file) contained into package B.

我有一个 java 包(包 A),我会检索包含在另一个包(包 B)中的文件。例如,假设进入包 AI 有一个名为 ClassA 的类。ClassA 需要访问包 B 中包含的 xml 文件(即配置文件)。

What is the procedure that I can use to access the configuration file from ClassA?

我可以使用什么程序从 ClassA 访问配置文件?

Thank you in advance. FA.

先感谢您。F A。

回答by Jerome

Use this:

用这个:

ClassA.class.getResourceAsStream("/packageB/yourfile.ext");

回答by David Grant

Use the importstatement.

使用import语句。

For example, to import class Barfrom package a.b.c.dinto your class in package a.b.c, you would write:

例如,要将Bar包中a.b.c.d的类导入到包中的类中a.b.c,您可以编写:

package a.b.c;

import a.b.c.d.Bar;

class Foo {
}

回答by KLE

In Java, you cannot get the files of a package, by reflexion or otherwise.

在 Java 中,您无法通过反射或其他方式获取包的文件。

Note that the classes of a package may be in many different folders (with different roots), in jars ..

请注意,包的类可能位于许多不同的文件夹中(具有不同的根),在 jars ..

But if you know your complete classpath, you can (complex task) search yourself in all these different locations...

但是如果你知道你的完整类路径,你可以(复杂的任务)在所有这些不同的位置搜索自己......