Method 1: Use ServletContext to read
Get the realpath of the configuration file, and then read it through the file stream or use the method getReaasurceAsStream().
Because the file path is read using ServletContext, the configuration file can be placed in the classes directory of WEB-INF, or in the application level and WEB-INF directory. The specific performance of file storage location in the eclipse project is: it can be placed under src, or under WEB-INF and Web-Root, etc. Because the path is read out and the file stream is used for reading, any configuration files can be read, including xml and properties. Disadvantages: Cannot read configuration information outside the servlet.
1. First create a dynamic javaweb project, the project directory is as follows:
2. Create a servlet (FileReader.java)
package com.xia.fileReader; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.text.MessageFormat; import java.util.Properties; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class FileReader extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { /** * response.setContentType("text/html;charset=UTF-8"); The purpose is to control the browser to decode UTF-8; * In this way, there will be no Chinese garbled*/ response.setHeader("content-type","text/html;charset=UTF-8"); readSrcDirPropCfgFile(response);//Read the db1.properties configuration file response.getWriter().println("<hr/>"); readWebRootDirPropCfgFile(response);//Read the db2.properties configuration file response.getWriter().println("<hr/>"); readWebRootDirPropCfgFile(response);//Read the db2.properties configuration file response.getWriter().println("<hr/>"); readSrcSourcePackPropCfgFile(response);//Read the db3.properties configuration file in the config directory under the src directory response.getWriter().println("<hr/>"); readWEBINFPropCfgFile(response);//Read the db4.properties configuration file in the JDBC directory under the WEB-INF directory} public void readSrcDirPropCfgFile(HttpServletResponse response) throws IOException { String path = "/WEB-INF/classes/db1.properties"; InputStream in = this.getServletContext().getResourceAsStream(path); Properties props = new Properties(); props.load(in); String driver = props.getProperty("jdbc.driver"); String url = props.getProperty("jdbc.url"); String username = props.getProperty("jdbc.username"); String password = props.getProperty("jdbc.password"); response.getWriter().println("Read the db1.properties configuration file in the src directory"); response.getWriter().println(MessageFormat.format( "driver={0},url={1},username={2},password={3}", driver,url, username, password)); } public void readWebRootDirPropCfgFile(HttpServletResponse response) throws IOException{ String path = "/db2.properties"; InputStream in = this.getServletContext().getResourceAsStream(path); Properties props = new Properties(); props.load(in); String driver = props.getProperty("jdbc.driver"); String url = props.getProperty("jdbc.url"); String username = props.getProperty("jdbc.username"); String password = props.getProperty("jdbc.password"); response.getWriter().println("Read the db2.properties configuration file in the WebRoot directory"); response.getWriter().println(MessageFormat.format( "driver={0},url={1},username={2},password={3}", driver,url, username, password)); } public void readSrcSourcePackPropCfgFile(HttpServletResponse response) throws IOException { String path = "/WEB-INF/classes/config/db3.properties"; String realPath = this.getServletContext().getRealPath(path); InputStreamReader reader = new InputStreamReader(new FileInputStream(realPath),"UTF-8"); Properties props = new Properties(); props.load(reader); String driver = props.getProperty("jdbc.driver"); String url = props.getProperty("jdbc.url"); String username = props.getProperty("jdbc.username"); String password = props.getProperty("jdbc.password"); response.getWriter().println("Read the db3.properties configuration file in the config directory under the src directory"); response.getWriter().println(MessageFormat.format( "driver={0},url={1},username={2},password={3}", driver,url, username, password)); } public void readWEBINFPropCfgFile(HttpServletResponse response) throws IOException { String path = "/WEB-INF/JDBC/db4.properties"; String realPath = this.getServletContext().getRealPath(path); System.out.println("realPath:"+realPath); System.out.println("contextPath:"+this.getServletContext().getContextPath()); InputStreamReader reader = new InputStreamReader(new FileInputStream(realPath),"UTF-8"); Properties props = new Properties(); props.load(reader); String driver = props.getProperty("jdbc.driver"); String url = props.getProperty("jdbc.url"); String username = props.getProperty("jdbc.username"); String password = props.getProperty("jdbc.password"); response.getWriter().println("Read the db4.properties configuration file in the JDBC directory under the WEB-INF directory"); response.getWriter().println(MessageFormat.format( "driver={0},url={1},username={2},password={3}", driver,url,username, password)); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } }3. Configure servlet (web.xml)
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>javaReaderFile</display-name> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> <welcome-file>default.html</welcome-file> <welcome-file>default.htm</welcome-file> <welcome-file>default.jsp</welcome-file> </welcome-file-list> <servlet> <servlet-name>FileReader</servlet-name> <servlet-class>com.xia.fileReader.FileReader</servlet-class> </servlet> <servlet-mapping> <servlet-name>FileReader</servlet-name> <url-pattern>/FileReader</url-pattern> </servlet-mapping> </web-app>
4. Test
Method 2: Use ResourceBundle class to read configuration information
The advantages are: the resource can be loaded in a fully qualified class name and read it directly, and the resource file can be read in non-Web applications.
Disadvantages: Only resource files under class src can be loaded and only .properties files can be read.
/** * Get all the data in the specified configuration file* @param propertyName * Call method: * 1. Place the configuration file under the resource source package without adding the suffix * PropertiesUtil.getAllMessage("message"); * 2. Place in the package * PropertiesUtil.getAllMessage("com.test.message"); * @return */ public static List<String> getAllMessage(String propertyName) { // Get the resource package ResourceBundle rb = ResourceBundle.getBundle(propertyName.trim()); // Get all key Enumeration<String> allKey = rb.getKeys(); // traverse the key and get value List<String> valList = new ArrayList<String>(); while (allKey.hasMoreElements()) { String key = allKey.nextElement(); String value = (String) rb.getString(key); valList.add(value); } return valList; }Method 3: Use ClassLoader to read configuration information
The advantages are: the configuration resource information can be read in non-Web applications, and any resource file information can be read.
Disadvantages: Only resource files under class src are loaded, and are not suitable for loading large files, otherwise it will cause jvm memory overflow
package com.xia.fileReader; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.Properties; public class ReadByClassLoader { public static void main(String[] args) throws IOException { readPropFileByClassLoad(); } public static void readPropFileByClassLoad() throws IOException { //Read the configuration file db3.properties InputStream in = ReadByClassLoader.class.getClassLoader().getResourceAsStream("config/db3.properties"); BufferedReader br = new BufferedReader(new InputStreamReader(in)); Properties props = new Properties(); props.load(br); for(Object s: props.keySet()){ System.out.println(s+":"+props.getProperty(s.toString())); } } }Method 4: PropertiesLoaderUtils tool class
/** * PropertiesLoaderUtils provided by Spring allows you to load property resources directly through the file address based on the classpath* The biggest advantage is: load the configuration file in real time, and it takes effect immediately after modification, without restarting */ private static void springUtil(){ Properties props = new Properties(); while(true){ try { props=PropertiesLoaderUtils.loadAllProperties("message.properties"); for(Object key:props.keySet()){ System.out.print(key+":"); System.out.println(props.get(key)); } } catch (IOException e) { System.out.println(e.getMessage()); } try {Thread.sleep(5000);} catch (InterruptedException e) {e.printStackTrace();} } }Modify Properties
/** * Pass the map of the key-value pair, update the properties file* * @param fileName * File name (placed in the resource source package directory), and requires the suffix * @param keyValueMap * Key-value pair Map */ public static void updateProperties(String fileName,Map<String, String> keyValueMap) { //The getResource method uses utf-8 to encode the path information. When there are Chinese and spaces in the path, it will convert these characters. In this way, the result is often not the real path we want. Here, the URLDecoder decode method is called to decode it to obtain the original Chinese and space paths. String filePath = PropertiesUtil.class.getClassLoader().getResource(fileName).getFile(); Properties props = null; BufferedWriter bw = null; try { filePath = URLDecoder.decode(filePath,"utf-8"); log.debug("updateProperties propertiesPath:" + filePath); props = PropertiesLoaderUtils.loadProperties(new ClassPathResource(fileName)); log.debug("updateProperties propertiesPath:" + filePath); props = PropertiesLoaderUtils.loadProperties(new ClassPathResource(fileName)); log.debug("updateProperties old:"+props); // Write property file bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filePath))); props.clear();// Clear the old file for (String key : keyValueMap.keySet()) props.setProperty(key, keyValueMap.get(key)); log.debug("updateProperties new:"+props); props.store(bw, ""); } catch (IOException e) { log.error(e.getMessage()); } finally { try { bw.close(); } catch (IOException e) { e.printStackTrace(); } } }Summarize
The above are the four methods of reading configuration files by JavaWeb that the editor introduces to you. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time. Thank you very much for your support to Wulin.com website!