1. 创建工具类
package com.ljw.util;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
/**
* Properties 配置文件操作类
*
*/
public class PropertiesUtil {
/**
* 获取 Properties 对象通过地址
* @param propertiesPath Properties 地址
* @return Properties 对象
*/
public static Properties getProperties(String propertiesPath){
try{
Properties properties = new Properties();
// 使用ClassLoader加载properties配置文件生成对应的输入流
InputStream in = PropertiesUtil.class.getClassLoader().getResourceAsStream(propertiesPath);
// 使用properties对象加载输入流
properties.load(in);
return properties;
}catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 获取 Properties 中 Key 的值
* @param propertiesPath Properties地址
* @param key 键
* @return 对应key的值
*/
public static String getPropertiesOnKey(String propertiesPath , String key){
try{
Properties properties = getProperties(propertiesPath);
return properties.getProperty(key);
}catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 写入properties信息
* @param propertiesPath Properties地址 地址 (在resources或java根目录下 例:jdbc.properties)
* @param maps 键值列表
* @author wlj
*/
public static void writeProperties(String propertiesPath, Map<String, String> maps) {
Properties prop = new Properties();
try {
propertiesPath = PropertiesUtil.class.getClassLoader().getResource("").getPath() + propertiesPath;
InputStream fis = new FileInputStream(propertiesPath);
prop.load(fis);
OutputStream fos = new FileOutputStream(propertiesPath);
for (String key : maps.keySet()) {
prop.setProperty(key, maps.get(key));
}
prop.store(fos, "updated");
} catch (IOException e) {
e.printStackTrace();
}
}
}
2. 调用
// 获取 src 下 ftp.properties
Properties ftp = getProperties("ftp.properties"); // 返回 Properties 对象
System.out.println(ftp.getProperty("ftpHost")); // 获取属性
System.out.println(ftp.getProperty("ftpUserName"));
System.out.println(ftp.getProperty("ftpPassword"));
System.out.println(ftp.getProperty("ftpPort"));
// 获取 config.pa 包下 pa.properties
Properties pa = getProperties("config/pa/pa.properties");
System.out.println(pa.getProperty("username")); // 获取属性
// 获取 config.test 包下 pa.properties
Properties test = getProperties("cfg/test/test.properties");
System.out.println(test.getProperty("host")); // 获取属性
// 获取 src 下 ftp.properties 文件的 ftpHost 属性
System.out.println(PropertiesUtil.getPropertiesOnKey("ftp.properties", "ftpHost")); // 返回对应的值
// 获取 config.pa 包下 pa.properties 文件的 username 属性
System.out.println(PropertiesUtil.getPropertiesOnKey("config/pa/pa.properties", "username"));
// 获取 config.test 包下 test.properties 文件的 host 属性
System.out.println(PropertiesUtil.getPropertiesOnKey("config/test/test.properties", "host"));
// 写入 src 下 ftp.properties
Map<String, String> maps = new HashMap<String, String>();
maps.put("ftpUserName", "sa");
maps.put("ftpPassword", "123");
PropertiesUtil.writeProperties("ftp.properties", maps);
3. properties 文件路径图