Difference between loading file with FileInputStream and getResourceAsStream() in java

This post will differentiate between loading file with FileInputStream and getResourceAsStream() in java, I have often seen developers creating mess between the two, this post will give you clear idea of when to use FileInputStream and getResourceAsStream() in java.

1) FileInputStream will load a the file from the path which is relative to your current working directory.
getResourceAsStream() will load a file from the path which is relative to your application's classpath. It’s generally used in web-applications.



2) FileInputStream is used to read a file from the local disk filesystem.
getResourceAsStream() locates and loads a file/resource using classloader of classname i.e using the ClassLoader of the class it is called on.  
Example - It can find the class embedded in jar file.



3) While working with FileInputStream you must prefer to give absolute paths as you cannot control the current working path.

While working with getResourceAsStream() you must use relative path as it uses relative path to your application's classpath.




4) Using FileInputStream to load file from given relative path may throw FileNotFoundException in web-applications (depends on your current working directory).
But using getResourceAsStream() to load file from same relative path may load the file successfully (depends on your application's classpath).


5) FileInputStream is generally used to load file when we have absolute path of file.
getResourceAsStream() is generally used to load file from some other java package when we don’t have absolute path of file.


More about  getResource method -
You may load a file using  ClassLoader#getResource(String name) which returns URL, OR ClassLoader#getResourceAsStream() which returns InputStream.


RELATED LINKS>

Find current working directory or current path in java


Directory operations - create, identify, delete, copy, traverse

Difference between getPath(), getAbsolute() and getCanonical() file path methods in java | Relative and Absolute path


Labels: Core Java
eEdit
Must read for you :