Public classJservletextendsHttpServlet { Public voiddoget (httpservletrequest request, httpservletresponse response)throwsservletexception, IOException {//Web-inf under theString path1 = Getservletcontext (). Getrealpath ("/web-inf/demo.xml"); //Lib under theString path2 = Getservletcontext (). Getrealpath ("/web-inf/lib/demo.xml"); //SRC under theString path3 = Getservletcontext (). Getrealpath ("/web-inf/classes/demo.xml"); //under the Cn.itcast.servlet.servlet_context bag.String Path4 = Getservletcontext (). Getrealpath ("/web-inf/classes/cn/itcast/servlet/servlet_context/demo.xml"); //in fact, in the above example, Path3 and Path4 have some trouble in both ways//introducing a way to get resources is the application of the. Class ==> class and ClassLoaderInputStream is = This. GetClass (). getResourceAsStream ("Demo.xml");//If you do not add "/" ==> is relative to the current (package) directory of the classInputStream Is2 = This. GetClass (). getResourceAsStream ("/demo.xml");//if Add "/" ==> "/" On behalf of Classes directory (SRC)//in the next classLoader there are methods ClassLoader is the loader of the class. ==> specifically to read the input stream of the class file//It also provides a way to read other files. (use ClassLoader not to read larger files)//This.getclass (). getClassLoader () ==> get ClassLoader for classInputStream Is3 = This. GetClass (). getClassLoader (). getResourceAsStream ("/demo.xml");//regardless of "/", relative to the classes directory, the same as the "/" in the class of the relative path is the same. //You can also get the absolute path of the file using class or ClassLoaderURL url = This. GetClass (). GetResource ("Demo.xml"); System.out.println (Url.getpath ()); }}
java--servlet get resources in several ways