Java Maven项目中资源文件的路径是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3104617/
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
What is the path to resource files in a Maven project?
提问by acarlow
In my Maven project, I have the following code in the main method:
在我的 Maven 项目中,我在 main 方法中有以下代码:
FileInputStream in = new FileInputStream("database.properties");
but always get a file not found error.
但总是得到一个找不到文件的错误。
I have put the file in src/main/resources and it is properly copied to the target/classes directory (I believe that is the expected behavior for Maven resources) but when actually running the program it seems it can never find the file. I've tried various other paths:
我已将文件放在 src/main/resources 中,并将其正确复制到 target/classes 目录(我相信这是 Maven 资源的预期行为),但是在实际运行程序时,它似乎永远找不到该文件。我尝试了各种其他路径:
FileInputStream in = new FileInputStream("./database.properties");
FileInputStream in = new FileInputStream("resources/database.properties");
etc. but nothing seems to work.
等等,但似乎没有任何效果。
So what is the proper path to use?
那么正确的使用路径是什么?
Based on "disown's" answer below, here was what I needed:
根据下面的“disown's”答案,这是我需要的:
InputStream in = TestDB.class.getResourceAsStream("/database.properties")
where TestDB
is the name of the class.
TestDB
类的名称在哪里。
Thanks for your help, disown!
感谢您的帮助,拒绝!
采纳答案by Alexander Torstling
You cannot load the file directly like that, you need to use the resource abstraction (a resource could not only be in the file system, but on any place on the classpath - in a jar file or otherwise). This abstraction is what you need to use when loading resources. Resource paths are relative to the location of your class file, so you need to prepend a slash to get to the 'root':
您不能像那样直接加载文件,您需要使用资源抽象(资源不仅可以在文件系统中,还可以在类路径上的任何位置 - 在 jar 文件中或其他地方)。这个抽象是你在加载资源时需要使用的。资源路径是相对于你的类文件的位置的,所以你需要在前面加上一个斜杠才能到达“根”:
InputStream in = getClass().getResourceAsStream("/database.properties");