robin robin - 3 months ago 15
Java Question

Issue while reading a file from WAR file

I have a war file with the below structure.

--js
--sum.js
--WEB-INF
--classes
---com
-----test
-----MyTest.class
--home.html


I am trying to read the js file in my MyTest.class file,But I am getting exception while reading it. I tried most of the solutions already mentioned in the stack.

I have tried

1)

String path = Thread.currentThread().getContextClassLoader().getResource("js/sum.js").getPath();
File f = new File(path);
System.out.println(f.getAbsolutePath());


First line is throwing nullpointer exception

2)

InputStream in =MyNashHornTest.class.getClassLoader().getResourceAsStream("/js/sum.js");
BufferedReader br = new BufferedReader(new InputStreamReader(in));


Second line is throwing null pointer exception

3)

InputStream in =MyNashHornTest.class.getClassLoader().getResourceAsStream("../../../../js/sum.js");
BufferedReader br = new BufferedReader(new InputStreamReader(in));


Second line is throwing null pointer exception

Please help me to resolve this issue.

Answer

For war files, don’t use the servlet container’s classloader, but use the ServletContext instead.

This method allows servlet containers to make a resource available to a servlet from any location, without using a class loader.

ServletContext context = getServletContext();
InputStream is = context.getResourceAsStream("/yourfilename.txt");

It is recommended to keep it under the /WEB-INF directory if you don’t want browers being able to access it.

The path must begin with a « / » and is interpreted as relative to the current context root. This method returns null if no resource exists at the specified path. For example ServletContext.getResourceAsStream(« WEB-INF/resources/yourfilename.cnf ») will return a nul exception, so be careful !

Why null pointer comes??

The path must begin with a "/" and is interpreted as relative to the current context root. This method returns null if no resource exists at the specified path. For example, using a path that doesn't start with a slash, You will get a null return value.

Details Description is given here: How to use ServletContext.getResourceAsStream(java.lang.String path)?

Resource Link:

HOW TO: Read a file from jar and war files (java and webapp archive) ?