java代码如何读写Properties文件呢?
下文笔者讲述读取Properties文件的方法分享,如下所示
读写Properties文件的实现思路
Java包中有一个Java.util.Properties类, 可用于读取Java的配置文件 Properties文件是一种键值对的形式存在的文件,我们使用java原生类即可对文件进行读写操作 Properties文件中可使用 # 添加注释信息 Properties文件中的方法: getProperty (String key): 用指定的键在此属性列表中搜索属性 也就是通过参数 key ,得到 key 所对应的 value。 load(InputStream inStream) 从输入流中读取属性列表(键和元素对) 通过对指定的文件(如说上面的 test.properties 文件) 进行装载来获取该文件中的所有键 - 值对 供getProperty ( String key) 来搜索。 setProperty(String key,String value) 调用Hashtable方法put 通过调用基类的put方法来设置 键 - 值对 store(OutputStream out, String comments) 使用load方法加载到Properties表中的格式 将此 Properties 表中的属性列表(键和元素对)写入输出流 与 load 方法相反,该方法将键 - 值对写入到指定的文件中去 clear() 清除所有装载键 - 值对例:Java代码操作Properties文件的示例
import java.io.BufferedInputStream; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; import java.util.Enumeration; import java.util.Properties; import org.apache.log4j.Logger; public class PropertieUtil { private static Logger logger = Logger.getLogger(PropertieUtil.class); private PropertieUtil() { } /** * 读取配置文件某属性 */ public static String readValue(String filePath, String key) { Properties props = new Properties(); try { // 注意路径以 / 开始,没有则处理 if (!filePath.startsWith("/")) filePath = "/" + filePath; InputStream in = PropertieUtil.class.getResourceAsStream(filePath); props.load(in); String value = props.getProperty(key); return value; } catch (Exception e) { logger.error(e); return null; } } /** * 打印配置文件全部内容(filePath,配置文件名,如果有路径,props/test.properties) */ public static void readProperties(String filePath) { Properties props = new Properties(); try { // 注意路径以 / 开始,没有则处理 if (!filePath.startsWith("/")) filePath = "/" + filePath; InputStream in = PropertieUtil.class.getResourceAsStream(filePath); props.load(in); Enumeration<?> en = props.propertyNames(); // 遍历打印 while (en.hasMoreElements()) { String key = (String) en.nextElement(); String Property = props.getProperty(key); logger.info(key + ":" + Property); } } catch (Exception e) { logger.error(e); } } /** * 将值写入配置文件 */ public static void writeProperties(String fileName, String parameterName, String parameterValue) throws Exception { // 本地测试特别注意,如果是maven项目,请到\target目录下查看文件,而不是源代码下 // 注意路径不能加 / 了,加了则移除掉 if (fileName.startsWith("/")) fileName.substring(1); String filePath = PropertieUtil.class.getResource("/").getPath()+fileName; // 获取配置文件 Properties pps = new Properties(); InputStream in = new BufferedInputStream(new FileInputStream(filePath)); pps.load(in); in.close(); OutputStream out = new FileOutputStream(filePath); // 设置配置名称和值 pps.setProperty(parameterName, parameterValue); // comments 等于配置文件的注释 pps.store(out, "Update " + parameterName + " name"); out.flush(); out.close(); } public static void main(String[] args) throws Exception { readProperties("jdbc.properties"); // logger.info(readValue("jdbc.properties", "JAVABLOG_WRITE_URL")); // writeProperties("test.properties", "test", "test"); } }
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。