提供一些常用的属性文件相关的方法
package com.opslab.util;
import org.apache.log4j.Logger;
import java.io.*;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
/**
* 提供一些常用的属性文件相关的方法
*/
public final class PropertiesUtil {
public static Logger logger = Logger.getLogger(PropertiesUtil.class);
/**
* 从系统属性文件中获取相应的值
*
* @param key key
* @return 返回value
*/
public final static String key(String key) {
return System.getProperty(key);
}
/**
* 根据Key读取Value
*
* @param filePath 属性文件
* @param key 需要读取的属性
*/
public final static String GetValueByKey(String filePath, String key) {
Properties pps = new Properties();
try (InputStream in = new BufferedInputStream(new FileInputStream(filePath))) {
pps.load(in);
return pps.getProperty(key);
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
public final static Map<String,String> properties(InputStream in){
Map<String,String> map = new HashMap<>();
Properties pps = new Properties();
try {
pps.load(in);
} catch (IOException e) {
logger.error("load properties error:"+e.getMessage());
}
Enumeration en = pps.propertyNames();
while (en.hasMoreElements()) {
String strKey = (String) en.nextElement();
String strValue = pps.getProperty(strKey);
map.put(strKey,strValue);
}
return map;
}
/**
* 读取Properties的全部信息
*
* @param filePath 读取的属性文件
* @return 返回所有的属性 key:value<>key:value
*/
public final static Map<String,String> GetAllProperties(String filePath) throws IOException {
Map<String,String> map = new HashMap<>();
Properties pps = new Properties();
try (InputStream in = new BufferedInputStream(new FileInputStream(filePath))) {
return properties(in);
}catch (IOException e){
logger.error("load properties error");
}
return map;
}
/**
* 写入Properties信息
*
* @param filePath 写入的属性文件
* @param pKey 属性名称
* @param pValue 属性值
*/
public final static void WriteProperties(String filePath, String pKey, String pValue) throws IOException {
Properties props = new Properties();
props.load(new FileInputStream(filePath));
// 调用 Hashtable 的方法 put,使用 getProperty 方法提供并行性。
// 强制要求为属性的键和值使用字符串。返回值是 Hashtable 调用 put 的结果。
OutputStream fos = new FileOutputStream(filePath);
props.setProperty(pKey, pValue);
// 以适合使用 load 方法加载到 Properties 表中的格式,
// 将此 Properties 表中的属性列表(键和元素对)写入输出流
props.store(fos, "Update '" + pKey + "' value");
}
}
相关文章
- 018 关联映射文件中<class>标签中的lazy(懒加载)属性
- Linux 文件基本属性
- WIN7下恼人的AppData——删除没用的缓存文件
- Word控件Spire.Doc 转换教程(十七): 加载纯文本 (txt) 文件并保存为 word 文档
- Linux 文件基本属性
- systemd Unit文件
- Javascript 文件的同步加载与异步加载
- Java 大文件分片上传
- Xamarin XAML语言教程隐藏文件使用Progress属性设置进度条
- Maven让资源文件处理插件能够解析资源文件中的Maven属性
- 设计一个健壮的大型文件下载系统
- multiple 属性,上传多个文件或图片
- WEB文件上传之apache common upload使用(一)
- PE文件结构及其加载机制
- 如何修改最大文件打开数ulimit
- 将xml文件转为txt文件
- 利用Jquery使用HTML5的FormData属性实现对文件的上传
- iOS开发 -- 为本地文件添加自定义属性的工具类
- 大数据编程技术基础实验八:Flume实验——文件数据Flume至HDFS
- 文件上传accept 属性 文件上传只能上传固定格式