实现的功能:
1、读取配置文件所有“键->值”信息
2、根据“键”设定“值”
3、根据“键”返回“值”
参考代码:
//package com.Config;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.Properties;
public class ConfigFile
{
/**
* 配置文件路径,配置文件名“server.properties”
*/
private static final String ConfigFilePath = "./server.properties";
/**
* @category 初始化配置文件-初始化为默认值
* */
private static void initConfigFile() {
Properties prop = new Properties();
try {
// 保存属性到b.properties文件,没有此配置文件将自动生成
FileOutputStream oFile = new FileOutputStream(ConfigFilePath, true);// true表示追加打开
prop.setProperty("port", "7556");//服务端端口:7556
prop.setProperty("dbUser", "root");//数据库用户名
prop.setProperty("dbPass", "123456");//数据库密码
prop.store(oFile, "New properties file");
oFile.close();
} catch (Exception e) {
System.out.println("初始化配置文件失败:" + e.getMessage());
}
}
/**
* @category 读取properties的全部信息
* */
public static void TraversalProperties() {
if(!new File(ConfigFilePath).exists())initConfigFile();
System.out.println("=========<readProperties-START>=========");
Properties props = new Properties();
try {
InputStream in = new BufferedInputStream(new FileInputStream(ConfigFilePath));
props.load(in);
Enumeration<?> en = props.propertyNames();
while (en.hasMoreElements()) {
String key = (String) en.nextElement();
String Property = props.getProperty(key);
System.out.println(key + " = " + Property);//键->值
}
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("=========<readProperties-END>=========");
}
/**
* @param parameterName 键
* @param parameterValue 值
* @category 写入properties信息,根据相应的“键”设定相应的“值”
* */
public static void writeProperties(String parameterName, String parameterValue) {
if(!new File(ConfigFilePath).exists())initConfigFile();
Properties prop = new Properties();
try {
InputStream fis = new FileInputStream(ConfigFilePath);
prop.load(fis);
OutputStream fos = new FileOutputStream(ConfigFilePath);
prop.setProperty(parameterName, parameterValue);
prop.store(fos, "Update New value");
} catch (IOException e) {
System.err.println("Visit " + ConfigFilePath + " for updating " + parameterName + " value error");
}
}
/**
* @param key 参数“port”、“dbUser”、“dbPass”
* @return 返回指定“键”的“值”
* */
public static String readProperties(String key) {
if(!new File(ConfigFilePath).exists())initConfigFile();
Properties props = new Properties();
try {
InputStream in = new BufferedInputStream(new FileInputStream(ConfigFilePath));
props.load(in);
String value = props.getProperty(key);
//System.out.println(key + " = " + value);
return value;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
配置文件server.properties中的内容:
#New properties file
#Mon Jan 27 15:43:52 CST 2020
dbPass=123456
port=7556
dbUser=root