示例:
database.properties配置文件:
hotelOrderRow=10
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306
username=root
password=666666
下面是以及和的形式读取配置文件中所有的属性及值
package org.utils;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.Properties;
public class ReadConfigManager {
private static ReadConfigManager readConfigManager;
// 单实例方法
public static synchronized ReadConfigManager getConfigManager() {
if (readConfigManager == null) {
readConfigManager = new ReadConfigManager();
}
return readConfigManager;
}
// 根据配置文件中属性的键获得对应的值
public Properties getValue() {
Properties properties = new Properties();
String configFile = "database.properties";
// 使用ClassLoader加载properties配置文件生成对应的输入流
InputStream is = ReadConfigManager.class.getClassLoader().getResourceAsStream(configFile);
try {
// 使用properties对象加载输入流
properties.load(is);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close(); // 关闭流
} catch (IOException e) {
e.printStackTrace();
}
}
// 获取key对应的value值
return properties;
}
private void printAllProperty(){
Enumeration en = getValue().propertyNames();
while (en.hasMoreElements()) { //遍历
String key = (String) en.nextElement(); //获取key值
String value = getValue().getProperty(key); //获取Value值
System.out.println(key+"="+value);
}
}
public static void main(String[] args) {
ReadConfigManager readConfigManager = new ReadConfigManager();
readConfigManager.printAllProperty();
}
}
读取配置文件单一值(已知键)
package org.utils;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.Properties;
public class ReadConfigManager {
private static ReadConfigManager readConfigManager;
// 单实例方法
public static synchronized ReadConfigManager getConfigManager() {
if (readConfigManager == null) {
readConfigManager = new ReadConfigManager();
}
return readConfigManager;
}
// 根据配置文件中属性的键获得对应的值
public String getValue(String key) {
Properties properties = new Properties();
String configFile = "database.properties";
// 使用ClassLoader加载properties配置文件生成对应的输入流
InputStream is = ReadConfigManager.class.getClassLoader().getResourceAsStream(configFile);
try {
// 使用properties对象加载输入流
properties.load(is);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close(); // 关闭流
} catch (IOException e) {
e.printStackTrace();
}
}
// 获取key对应的value值
return properties.getProperty(key);
}
public static void main(String[] args) {
ReadConfigManager readConfigManager = new ReadConfigManager();
String row = readConfigManager.getValue("hotelOrderRow");
System.out.println("hotelOrderRow = "+row);
}
}
注意:在使用中遇到的最大的问题可能是配置文件的路径问题,如果配置文件入在当前类所在的包下,那么需要使用包名限定。
更多读取方式方法参考:https://www.cnblogs.com/sebastian-tyd/p/7895182.html