1

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?

Criel
  • 805
  • 1
  • 14
  • 32
  • 1
    read [this](http://stackoverflow.com/questions/676250/different-ways-of-loading-a-file-as-an-inputstream) , well this has been already explained – Gaurav Mar 29 '16 at 15:52
  • 1
    Do not use File.separator. Use the / instead. – Keno Mar 29 '16 at 15:53
  • 2
    WEB-INF is not on your web app's classpath. But, WEB-INF/classes is on your web app's classpath. So, put the file file.props at WEB-INF/classes/file.prop – rickz Mar 29 '16 at 15:56

2 Answers2

0

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().

John Bollinger
  • 160,171
  • 8
  • 81
  • 157
0

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.

Christopher Schultz
  • 20,221
  • 9
  • 60
  • 77