简体   繁体   中英

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.

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) ?

You can get resources from the class path with ClassLoader.getResource or from the web root directory with ServletContext.getResource .

In a war, you use the former to access ressources stored under WEB-INF/classes , or in jars under WEB-INF/lib , and the former for what lies directly at the root of the web application.

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