配置文件PropertiesUtil
配置文件 system.properties
jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc\:mysql\://localhost\:3306/yzuzhang jdbc.username=root jdbc.password=123456
具体实现代码:
package com.javaweb.utils; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.Properties; import org.apache.commons.io.IOUtils; public class PropertiesUtil { /** * @param key * @return * @throws IOException */ public static String readProperties(String key){ String value = null; InputStream inputStream = null; try { Properties p = new Properties(); String path = Thread.currentThread().getContextClassLoader() .getResource("config/system.properties").getPath(); //路径也可以这样获取 path = PropertiesUtil.class.getClassLoader().getResource("config/system.properties").getPath(); System.out.println(path); inputStream = new FileInputStream(path); if (null != inputStream) { p.load(inputStream); value = p.getProperty(key); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { IOUtils.closeQuietly(inputStream); } return value; } /** * @param key * @return * @throws IOException */ public static String getProperty(String key){ String value = null; InputStream inputStream = null; try { Properties p = new Properties(); inputStream = PropertiesUtil.class.getClassLoader(). getResourceAsStream("config/system.properties"); if (null != inputStream) { p.load(inputStream); value = p.getProperty(key); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { IOUtils.closeQuietly(inputStream); } return value; } public static void main(String[] args) throws IOException { System.out.println("jdbc.username === "+getProperty("jdbc.username")); System.out.println("jdbc.driver === "+readProperties("jdbc.driver")); } }
控制台输出的结果如下:
jdbc.username === root /E:/Workspaces/yzuzhang/WebRoot/WEB-INF/classes/config/system.properties jdbc.driver === com.mysql.jdbc.Driver

浙公网安备 33010602011771号