ybc

 

读取properties文件的简单示例

package ybc;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;


public class GetFile {

private Properties userList;


public GetFile(String name,String password ) {//构造函数
super();
Logger log = Logger.getLogger(GetFile.class);
log.debug("构造函数");
userList=new Properties();
userList.setProperty(name,password);

}

public Properties getUserList() throws IOException

{

// 判断 userList 是否为空,如果为空,则重新加载属性文件

if (userList == null)

{

// 首先检查保存用户名、密码的属性文件是否存在

File f = new File("d:/userFile.txt");

// 如果文件不存在,则创建文件

System.out.print("文件的路径:"+f.getAbsolutePath()+"\n");

if (!f.exists())

f.createNewFile();

// 创建新的 Properties 实例,该实例保存了用户名、密码对

userList = new Properties();

// 从属性文件中加载所有的用户名、密码

userList.load(new FileInputStream(f));

}

// 返回保存用户名、密码对的 Properties 实例

return userList;
}

public boolean saveUserList()throws IOException

{

// 如果用户列表为空,则无法保存用户

if (userList == null)

{

return false;

}

// 调用 Properties 类的 store 方法将用户列表保存到文件输出流

userList.store(new FileOutputStream("d:/userFile.txt"), "userList");

return true;

}

public static void main(String args[]){
System.out.println("执行的第一步:保存键值对到文本文件中");
GetFile g= new GetFile("ybc","ybc");

try{if(g.saveUserList())
System.out.print("save successfull!\n");
}catch(IOException e){
System.out.print(e.toString());
}
System.out.println("执行的第二步:取文本文件中的key对应的值");
//用下面这个类get Userlist
try{
g.userList=null;//这句不加的话,它就没真正从文本文件中取,不信你试试注释这句,然后运行就看不到打印的文件路径了!!!
System.out.println("从文件中get的user键:ybc的值:"+g.getUserList().get("ybc")+" ");
}catch(IOException e){
System.out.print(e.toString());
}
}
// 通过上面的演示你可以简单了解:File、FileOutputStream、FileInputStream和Properties类的使用
// 以上只是简单的演示了下properties文件的读取过程,要深入了这个类可以参考java 的 Api文档
}

posted on 2008-03-28 09:19 ybc 阅读(257) 评论(0)  编辑  收藏


只有注册用户登录后才能发表评论。


网站导航:
 

导航

统计

常用链接

留言簿(1)

随笔档案

文章分类

文章档案

搜索

最新评论

阅读排行榜

评论排行榜