Property

XT4625 2009-03-30 09:13:38
如何用property访问*.properties中的所有内容?
如:文件名:ATM.properties文件的中有内容如下:
username=a1
password=1
username=a2
password=2
username=a3
password=3
默认情况下我只能访问最后一个,如何将前面的内容也访问到?
...全文
58 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
quanjinzhang 2009-03-31
  • 打赏
  • 举报
回复
我写的一个例子,不过这里也会覆盖掉,需要你通过hashmap之类的类来存放所有值
否则:mAllProperties.setProperty(key, value);会覆盖掉以前的属性键值对。
/**
* 通过读取配置文件路径对应的配置文件,获取属性键值对
* @return
*/
private boolean getProperties(String tPropertieFilePath){
File myPropertyfile = null;
boolean returnValue = true;
try {
myPropertyfile = new File(tPropertieFilePath);
if(!myPropertyfile.exists())
{
System.out.println("没有找到属性配置文件“" + tPropertieFilePath
+ "”,请在当前目录下创建config目录,并将名为config.properties的属性配置文件存放到该目录下!");
}else if(!myPropertyfile.canRead())
{
System.out.println("无法读取设定的属性配置文件“" + tPropertieFilePath +"”,请设定属性配置文件的属性为可读!");
}
FileReader fr = null;
BufferedReader br = null;
fr = new FileReader(myPropertyfile);
br = new BufferedReader(fr);
String line = br.readLine();
int i=0;
while(line!=null){
line = line.trim();
int equalIndex = line.indexOf("=");
if(equalIndex>0 && !line.startsWith("#"))
{
String key = line.substring(0, equalIndex).trim().toLowerCase();
String value = line.substring(equalIndex+1, line.length()).trim();
if(!key.equals("") && !value.equals(""))
{
i++;
if(i==1){
mAllProperties = new Properties();
}
mAllProperties.setProperty(key, value);
}
}
line = br.readLine();
}
br.close();
fr.close();
if(mAllProperties.isEmpty())
{
System.out.println("属性配置文件“" + tPropertieFilePath + "”里没有任何属性配置信息,请重新配置相关信息!");
}
}
catch (FileNotFoundException e)
{
e.printStackTrace();
System.out.println("没有找到属性配置文件“" + tPropertieFilePath
+ "”,请在当前目录下创建config目录,并将名为initconfig.properties的属性配置文件存放到该目录下!");
returnValue = false;
} catch (IOException e) {
e.printStackTrace();
System.out.println("读取属性配置文件“" + tPropertieFilePath + "”的内容时发生IO错误!");
returnValue = false;
}
return returnValue;
}
danielzhan 2009-03-31
  • 打赏
  • 举报
回复
properties的父类是hashtable,所以properties中是不能有重名的key的.
得自己写一个类似properties的class,要不就干脆把文件作为txt来读,再自己解析内容.
Study_Work_2009 2009-03-31
  • 打赏
  • 举报
回复
up
fireinjava 2009-03-31
  • 打赏
  • 举报
回复
public class Test {

private static Properties properties = new Properties();
static {
try {
properties.load(GlobalError.class.getClassLoader().getResourceAsStream("src/ATM.properties"));//这边路径自己要配下
} catch (IOException e) {

}
}


public static void main(String args[]) {
System.out.println(properties.get("username"));//用get(key)
}
}
quanjinzhang 2009-03-30
  • 打赏
  • 举报
回复
1、为什么必须使用一样的属性名称呢?如果不使用一样的属性名称,问题不就解决了吗?
2、自己通过java.io.*中的FileReader等去一行一行读取,肯定能都获取到所有值了。

58,453

社区成员

发帖
与我相关
我的任务
社区描述
Java Eclipse
社区管理员
  • Eclipse
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧