PropertiesOperation

本文介绍了一种在Java中操作Properties文件的方法,包括通过键获取值及更新Properties文件内容的功能实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

public class PropertiesOperation
{

/**
* 通过key 获取对应的value(url)
*
* @param String key[对应的索引]
* @return String value[返回key所对应的value]
* @throws
* @since TianTian
*/
public static String getValueByKeyFromProperties(String path,String key)
{
String value = null;
InputStream inputStream = null;
try
{
Properties properties = new Properties();
inputStream = PropertiesOperation.class.getResourceAsStream(path);
properties.load(inputStream);
value = properties.getProperty(key);
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
try
{
if (null != inputStream)
{
inputStream.close();
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
return value;
}

/*
* 写入properties信息
*/
public static void writeProperties(Context context,String path,Map<String, String> parameters)
{
Properties props = new Properties();
try {
props.load(context.openFileInput(path));
OutputStream out = context.openFileOutput(path,Context.MODE_PRIVATE);
// Enumeration<?> e = props.propertyNames();
// if(e.hasMoreElements())
// {
// while (e.hasMoreElements())
// {
// String s = (String) e.nextElement();
// if (!s.equals(keyName))
// {
// props.setProperty(s, props.getProperty(s));
// }
// }
// }
Set<String> keys = parameters.keySet();
for (Iterator<String> iterator = keys.iterator(); iterator.hasNext();)
{
String key = (String) iterator.next();
props.setProperty(key, parameters.get(key));

/*
* 更新原值
*/
props.store(out, "Update '" + key + "' value");
}
// props.setProperty(keyName, keyValue);
// props.store(out, null);
// String value = props.getProperty(keyName);
// System.out.println(keyName + " "+value);
}
catch (FileNotFoundException e) {
Log.v("system", "location.properties Not Found Exception");
}
catch (IOException e) {
Log.v("system", "location.properties IO Exception");
}
}

/**
* 写入properties信息
*/
public static void writeProperties(String filePath, Map<String, String> parameters)
{
Properties prop = new Properties();
try
{
InputStream fis = new FileInputStream(filePath);
prop.load(fis);
OutputStream fos = new FileOutputStream(filePath);
Set<String> keys = parameters.keySet();
for (Iterator<String> iterator = keys.iterator(); iterator.hasNext();)
{
String key = (String) iterator.next();
prop.setProperty(key, parameters.get(key));

/*
* 更新原值
*/
prop.store(fos, "Update '" + key + "' value");
}
}
catch (IOException e)
{
System.out.println("Visit " + filePath + " for updating value error");
e.printStackTrace();
}
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值