getResourceAsStream() vs FileInputStream


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?


solution:

The java.io.File and consorts acts on the local disk file system. The root cause of your problem is that relative  paths in java.io are dependent on the current working directory. I.e. the directory from which the JVM (in your case: the webserver) is started. This may for example be C:/Tomcat/bin  or something entirely different, but thus not C:/Tomcat/webapps/contextname  or whatever you'd expect it to be. The working directory is in no way programmatically controllable. You should never use relative paths with them. Always use absolute paths. E.g. C:/full/path/to/file.ext.

You don't want to hardcode or guess the absolute path in Java (web)applications. That's only portability trouble. The normal practice is to place those kind of resoures in the classpath (or to add its full path to the classpath) and use ClassLoader#getResource() or ClassLoader#getResourceAsStream() instead. It is able to locate files relative to the "root" of the classpath, as you by coincidence figured out. In webapplications (or any other application which uses multiple classloaders) it's recommend to use the ClassLoader as returned by Thread.currentThread().getContextClassLoader() for this.

Another alternative in webapps is the ServletContext#getResource() and its counterpart ServletContext#getResourceAsStream(). It is able to access files located in the public web folder of the webapp project, including the /WEB-INF folder. The ServletContext is available in servlets by the inherited getServletContext() method, you can call it as-is. It however requires that the WAR is been exploded by the servletcontainer.

Sample in attach

你可能感兴趣的:(tomcat,C++,c,Web,ext)