java 找不到属性文件 - 如何将其定位为资源?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15894642/
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
Properties file not found - how to locate it as resource?
提问by coure2011
I have a properties file at location (from netbeans project explorer)
我在某个位置有一个属性文件(来自 netbeans 项目资源管理器)
-MyTest
+Web Pages
+Source Packages
-Test Packages
-<default package>
+Env.properties <---- Here it is
+com.mycomp.gts.test
+com.mycomp.gts.logintest
.....
....
Now when I am trying to find this file using code
现在,当我尝试使用代码查找此文件时
InputStream propertiesInputStream = getClass().getResourceAsStream("Env.properties");
ENV.load(propertiesInputStream);
Its throwing java.lang.NullPointerException
它的投掷 java.lang.NullPointerException
回答by Perception
You cannot use the class as a reference to load the resource, because the resource path is notrelative to the class. Use the class loader instead:
不能使用类作为加载资源的引用,因为资源路径与类无关。改用类加载器:
InputStream propertiesInputStream = getClass().getClassLoader()
.getResourceAsStream("Env.properties");
ENV.load(propertiesInputStream);
Or alternatively, you can use the context class loader of the current thread:
或者,您可以使用当前线程的上下文类加载器:
InputStream propertiesInputStream = Thread.currentThread()
.getContextClassLoader().getResourceAsStream("Env.properties");
ENV.load(propertiesInputStream);
回答by Hunter Zhao
String basePath = PropertiesUtil.class.getResource("/").getPath();
InputStream in = new FileInputStream(basePath + "Env.properties");
pros.load(in);
Good luck:)
祝你好运:)
回答by sk2212
Try to get absolute path with:
尝试获取绝对路径:
String absolute = getClass().getProtectionDomain().getCodeSource().getLocation().toExternalForm();
You can print out the string absolute
and try to substring it to your path of your properties file.
您可以打印出字符串absolute
并尝试将其子字符串化到您的属性文件的路径中。