Here's a summary of the 3 methods to get the resource file
- ServletContext
- Class
- ClassLoader
The location of the file
1. ServletContext
public void doget (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException { PrintWriter pw = Response.getwriter (); ServletContext context = This.getservletcontext ();/** * Get resource files under different paths * ServletContext is relative to the root of the project, here is webcontent */ InputStream Inputa = Context.getresourceasstream ("/a.txt"); InputStream InputB = Context.getresourceasstream ("/ Web-inf/classes/cn/zydev/b.txt "); InputStream INPUTC = Context.getresourceasstream ("/web-inf/classes/c.txt ");/** * Get the real disk path */string Realpath = Context.getrealpath ("/web-inf/classes/c.txt"),/** * Get files in the specified directory (including directory, depth is level 1) */set< string> RSC = context.getresourcepaths ("/web-inf"); String a = ioutils.tostring (Inputa); String B = ioutils.tostring (InputB); String C = ioutils.tostring (INPUTC);p W.print (A + "<br/>");p W.print (b + "<br/>");p w.print (c+ "<br/>") ;p w.print (realpath+ "<br/>");p w.println (RSC);}
The results show:
2. ClassLoader
The use of ClassLoader is relative to the classes
protected void doget (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException { PrintWriter pw = Response.getwriter ();/** * ClassLoader is relative to classes reference * The first slash can be written or not./(familiarity with Linux should be clear) */classloader CL = This.getclass (). getClassLoader (); InputStream Inputa = Cl.getresourceasstream ("/". /.. /a.txt "), InputStream InputB = Cl.getresourceasstream ("/cn/zydev/b.txt "); InputStream INPUTC = Cl.getresourceasstream ( "/c.txt"); String a = ioutils.tostring (Inputa); String B = ioutils.tostring (InputB); String C = ioutils.tostring (INPUTC);p W.print (A + "<br/>");p W.print (b + "<br/>");p w.print (c+ "<br/>") ;}
Get results:
3. Class
The forward slash of the path indicates relative to the current class, without a slash in relation to the classes
protected void doget (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException { PrintWriter pw = Response.getwriter (); Class cs = This.getclass ();//No slash indicates relative to Class (Cservlet) InputStream Inputa = Cs.getresourceasstream (": /.. /.. /.. /a.txt "); InputStream InputB = Cs.getresourceasstream (" B.txt ");//Slash, relative to classesinputstream INPUTC = Cs.getresourceasstream ("/c.txt"); String a = ioutils.tostring (Inputa); String B = ioutils.tostring (InputB); String C = ioutils.tostring (INPUTC);p W.print (A + "<br/>");p W.print (b + "<br/>");p w.print (c+ "<br/>") ;}
Get results:
Summary of methods for obtaining resource files in Java