I was trying to load a file in a webapp, and I was getting a FileNotFound
exception when I used FileInputStream
. However, using the same path, I was able to load the file when I did getResourceAsStream()
.
What is the difference between the two methods, and why does one work while the other doesn't?
This question is related to
java
file-io
web-applications
fileinputstream
getResourceAsStream
is the right way to do it for web apps (as you already learned).
The reason is that reading from the file system cannot work if you package your web app in a WAR. This is the proper way to package a web app. It's portable that way, because you aren't dependent on an absolute file path or the location where your app server is installed.
The FileInputStream
class works directly with the underlying file system. If the file in question is not physically present there, it will fail to open it. The getResourceAsStream()
method works differently. It tries to locate and load the resource using the ClassLoader
of the class it is called on. This enables it to find, for example, resources embedded into jar
files.
classname.getResourceAsStream() loads a file via the classloader of classname. If the class came from a jar file, that is where the resource will be loaded from.
FileInputStream is used to read a file from the filesystem.
I am here by separating both the usages by marking them as File Read(java.io) and Resource Read(ClassLoader.getResourceAsStream()).
File Read - 1. Works on local file system. 2. Tries to locate the file requested from current JVM launched directory as root 3. Ideally good when using files for processing in a pre-determined location like,/dev/files or C:\Data.
Resource Read - 1. Works on class path 2. Tries to locate the file/resource in current or parent classloader classpath. 3. Ideally good when trying to load files from packaged files like war or jar.
FileInputStream will load a the file path you pass to the constructor as relative from the working directory of the Java process. Usually in a web container, this is something like the bin
folder.
getResourceAsStream()
will load a file path relative from your application's classpath.
Source: Stackoverflow.com