1 PackageGz.itcast.b_resource;2 3 Importjava.io.IOException;4 ImportJava.io.InputStream;5 Importjava.util.Properties;6 7 Importjavax.servlet.ServletException;8 ImportJavax.servlet.http.HttpServlet;9 Importjavax.servlet.http.HttpServletRequest;Ten ImportJavax.servlet.http.HttpServletResponse; One /** A * Read resource files under Web application (e.g. properties) - * @authorAPPle - */ the Public classResourcedemoextendsHttpServlet { - - Public voiddoget (httpservletrequest request, httpservletresponse response) - throwsservletexception, IOException { + /** - *. Run the directory on behalf of the Java command. Where is the Java Run command?? Under the Tomcat/bin directory + * Conclusion: In a Web project, the. Rep starts under the Tomcat/bin directory, so this relative path cannot be used. A */ at - - //read the file. Do not read this under the Web project. Because. indicated in the Tomcat/bin directory - /*File File = new file ("./src/db.properties"); - FileInputStream in = new FileInputStream (file);*/ - in /** - * Methods for loading resource files under Web application to */ + /** - * 1. Getrealpath read, returns the absolute path of the resource file the */ * /*String Path = This.getservletcontext (). Getrealpath ("/web-inf/classes/db.properties"); $ System.out.println (path);Panax Notoginseng File File = new file (path); - FileInputStream in = new FileInputStream (file);*/ the + /** A * 2. getResourceAsStream () Gets the resource file and returns the input stream the */ +InputStream in = This. Getservletcontext (). getResourceAsStream ("/web-inf/classes/db.properties"); - $ $Properties prop =NewProperties (); - //Read Resource file - prop.load (in); the -String user = Prop.getproperty ("User");WuyiString Password = prop.getproperty ("Password"); theSystem.out.println ("user=" +user); -System.out.println ("password=" +password); Wu - } About $}
Read resource files under Web Apps (for example, properties)