java的Properties 文件快速、方便存取处理

Properties类,用于存取java配置文件,以键值对的形式存文件;

public class Properties extends Hashtable<Object,Object>,它是继承自Hashtable的;

实际使用:在项目中有一些值需要存储,但是又没有必要设计对应数据库,这时存文件的方式就可以很好的解决问题!

保存文字,文件内容如下:


更多java工具类下载


/**
 * 文件读写(键值对)工具类
 * 
 * @author
 * 
 */
public class PropertiesFileUitl {

public static void main(String[] args) {
saveAndRead();
}

/**
* 存文件和读取文件
*/
private static void saveAndRead() {
// 获取项目部署目录
// String path = request.getServletContext().getRealPath("WEB-INF") + File.separator + fileName;

String path = "D://properties.txt";
// 存文件
// public class Properties extends Hashtable<Object,Object>
// Properties类,用于读取java配置文件, 表示了一个持久的属性集。
Properties properties = new Properties();
properties.setProperty("name", "Peter.pan");
properties.setProperty("age", "26");
properties.setProperty("add", "Sichuan.chengdu");
save(properties, path);


// 读文件
Map<String, String> map = read(path);
for (Entry<String, String> entry : map.entrySet()) {
System.out.println(entry.getKey() + " : " + entry.getValue());
}
}

/**
* 使用properties保存文本到文件中(键值对)
*/
public static void save(Properties properties, String filePath) {
try {
OutputStream outputStream = new FileOutputStream(new File(filePath)); // 将键值内容保存至指定文件
properties.store(outputStream, "temp_info");
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 读取指定文件的内容(键值对)

* @param filePath
* @return
*/
public static Map<String, String> read(String filePath) {
Map<String, String> map = new HashMap<String, String>();
try {
Properties prop = new Properties(); // 从文件中获取信息
FileInputStream fis = new FileInputStream(new File(filePath));
prop.load(fis); // 加载文件流的属性
Enumeration<?> keys = prop.propertyNames(); // 返回属性列表中所有键的枚举
while (keys.hasMoreElements()) { // 遍历枚举,获取键值信息
String key = (String) keys.nextElement();
String value = prop.getProperty(key);
map.put(key, value);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return map;
}
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

未来的我比现在的我更优秀

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值