3

I'm trying to read in an html file as a string using InputStream but no matter what I try I keep getting a null pointer exception. The File I am trying to read is at "/war/index.html" and the code to read it in looks like this:

File f = new File(path);
        ServletContext context = getServletContext();
        InputStream is = context.getResourceAsStream(f.getAbsolutePath());
        int data = is.read();

As soon as I call is.read() it gives me a NullPointerException. Any help is appreciated thanks!

LeeFoster
  • 75
  • 1
  • 6
  • You may find an answer here.... http://stackoverflow.com/questions/2797162/getresourceasstream-is-always-returning-null – smallworld May 31 '13 at 03:05

1 Answers1

1

Here seems to be 2 issues combined:

  • by default when you create file with relative path, working directory in this case is java.dir, which in most cases is not the same, as webapps folder of web-container
  • you seem to have extra war indicator in your path.

Please check how ServletContext resolves files.

So you simply need to use:

ServletContext context = getServletContext();
InputStream is = context.getResourceAsStream("/index.html");
n1ckolas
  • 4,380
  • 3
  • 37
  • 43