Java 使用 ClassLoader 的绝对路径 getResourceAsStream()
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20127017/
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
Use Absolute path for ClassLoader getResourceAsStream()
提问by user3018487
I am trying to use ClassLoader getResourceAsStream()
我正在尝试使用 ClassLoader getResourceAsStream()
My Direcory structure is like below:
我的目录结构如下:
Project1
-src
-main
-java
-webapp
-WEB-INF
-MYLOC
-someprops.properties
For classloader.getResourceAsStream("MYLOC/someprops.properties")works fine.
对于classloader.getResourceAsStream("MYLOC/someprops.properties")工作正常。
But now I have to move the properties file outside of the .war, like in C:\someprops.properties
但是现在我必须将属性文件移到 .war 之外,例如 C:\someprops.properties
But, classloader.getResourceAsStream("C:\someprops.properties")does not work.
Can it not use an absolute path?
但是,classloader.getResourceAsStream("C:\someprops.properties")不起作用。不能使用绝对路径吗?
采纳答案by Ian Roberts
If you have a native file path then you don't need to use getResourceAsStream, just create a FileInputStreamin the normal way.
如果您有本机文件路径,则不需要使用getResourceAsStream,只需FileInputStream以正常方式创建。
Properties props = new Properties();
FileInputStream in = new FileInputStream("C:\someprops.properties");
try {
props.load(in);
} finally {
in.close();
}
(you may want to wrap the FileInputStreamin a BufferedInputStreamif the file is large)
(如果文件很大,您可能希望将其包装FileInputStream在 a 中BufferedInputStream)
回答by benjamin.d
The method classloader.getResourceAsStreamlooks up resources on the classpath. If you want to load your someprops.propertiesfile with classloader.getResourceAsStreamthen add it to your classpath. Otherwise, if this is a properties file, you could always use the Properties.loadmethod.
该方法classloader.getResourceAsStream在类路径上查找资源。如果要加载someprops.properties文件,classloader.getResourceAsStream请将其添加到类路径中。否则,如果这是一个属性文件,您始终可以使用Properties.load方法。

