Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use Absolute path for ClassLoader getResourceAsStream()

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?

like image 802
user3018487 Avatar asked Nov 21 '13 16:11

user3018487


People also ask

What is the declaration for Java classloader getsystemresourceasstream?

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.

What is the return value of getresourceasstream () method?

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.

How to get absolute Classpath in Java?

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.

How to load resources from the classpath?

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.


2 Answers

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.

like image 98
benjamin.d Avatar answered Oct 30 '22 23:10

benjamin.d


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)

like image 32
Ian Roberts Avatar answered Oct 30 '22 23:10

Ian Roberts