I am trying to use 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.
But now I have to move the properties file outside of the .war, like in C:\someprops.properties
But, classloader.getResourceAsStream("C:\someprops.properties")
does not work.
Can it not use an absolute path?
Following is the declaration for java.lang.ClassLoader.getSystemResourceAsStream () method name − This is the resource name. This method returns an input stream for reading the resource, or null if the resource could not be found.
Return Value: This method returns the specified resource of this class in the form of InputStream objects. Exception This method throws: Below programs demonstrate the getResourceAsStream () method.
So basically two methods named: getResource () and getResourceAsStream () are used to load the resources from the classpath. These methods generally return the URL’s and input streams respectively. These methods are present in the java.lang.Class package. So here we are taking getting absolute classpath using classLoader () method.
To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course. So basically two methods named: getResource () and getResourceAsStream () are used to load the resources from the classpath. These methods generally return the URL’s and input streams respectively.
The method classloader.getResourceAsStream
looks up resources on the classpath. If you want to load your someprops.properties
file with classloader.getResourceAsStream
then add it to your classpath. Otherwise, if this is a properties file, you could always use the Properties.load method.
If you have a native file path then you don't need to use getResourceAsStream
, just create a FileInputStream
in the normal way.
Properties props = new Properties();
FileInputStream in = new FileInputStream("C:\\someprops.properties");
try {
props.load(in);
} finally {
in.close();
}
(you may want to wrap the FileInputStream
in a BufferedInputStream
if the file is large)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With