简体   繁体   中英

GetResourceAsStream returning null, file exists

I know there are many topics out there for this but I have seem to have tried everything. I can put my file name in there and it finds it if there is a src folder,

InputStream is = context.class.getClassLoader().getResourceAsStream("file.props");

but when we put it on an apache server, a src folder is not automatically created, so it isn't finding it. I have tried placing it directly in the web-inf folder and

InputStream is = context.class.getClassLoader().getResourceAsStream("/WEB-INF" + File.separator + "file.props");

But this is always returned as null. What is the reason for this? The file exists there, why can't it find it?

You appear to be using the wrong ClassLoader . Invoking context.class.getClassLoader() provides the ClassLoader with which the ServletContext class ( context.class ) was loaded. What you want is the ClassLoader for the web application 's classes, which would be context.getClassLoader() .

Don't use the ClassLoader if you want to load your file from /WEB-INF . Instead, use the ServletContext 's method for just that purpose:

// In your servlet e.g. doGet method
ServletContext app = super.getServletContext();
InputStream in = app.getResourceAsStream("/WEB-INF/file.props");

Note that using / is okay regardless of the OS, filesystem, etc.

If you really want to use the ClassLoader , take @rickz's advice and move your file.props into WEB-INF/classes .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM