java中.properties属性文件的使用案例源码

来源:互联网 发布:大众软件最后一期 编辑:程序博客网 时间:2024/05/08 16:27

一、描述

java中的.properties属性文件的正确使用可以解决很多问题,比如一个登录界面要做一个记住用户登录过的用户名和密码并且放在本地方便用户登录。

二、操作步骤

1.  打开eclipse工程文件目录下的XX.properties文件,如果没有就创建一个

2. 以键-值对的方式记录用户最近登录过的用户名--密码,添加一个键值对

3. 移除一个键-值对

4. 保存这个属性文件

5. 获取属性文件的所有键

6. 获取指定键的属性值

二、源代码

//在工作主目录下(即eclipse项目目录下创建一个属性文件,例如用来记录用户最近登录过的用户名和密码)File file = new File(System.getProperty("user.dir")+ "\\login.properties");if (!file.exists()) {//如果文件不存在就先创建file.createNewFile();}properties.load(new FileInputStream(file)); //加载属性文件//获取属性文件中的某个属性,<span style="font-family: arial; line-height: 20px; background-color: rgb(255, 255, 255);">搜索此属性中指定键的属性值</span>if (properties.getProperty("firstname") == null) {//设置属性文件中的某个属性properties.setProperty("firstname", "");}ArrayList<String> accountList = new ArrayList<String>();@SuppressWarnings("unchecked")//获取属性文件的所有key,放在一个String类型的枚举类型中Enumeration<String> en = (Enumeration<String>) properties.propertyNames();while (en.hasMoreElements()) {String key = (String) en.nextElement();accountList.add(key);}//将ArrayList<String>转换为字符串数组,将它放在一个下拉列表中供用户选择String[] nameHistory = (String[]) accountList.toArray(new String[1]);JComboBox accountBox = new JComboBox(nameHistory);// 创建一个新的键值对,记录最后登录名为首选登录名,每次登录的默认选择项properties.put("firstname", sname);properties.remove(keyName); //删除一个keyName为键的记录//保存属性文件,并捕获相应的异常try {properties.store(new FileOutputStream("login.properties"), null);} catch (FileNotFoundException ex) {Logger.getLogger(LoginFrame.class.getName()).log(Level.SEVERE, null, ex);} catch (IOException ex) {Logger.getLogger(LoginFrame.class.getName()).log(Level.SEVERE, null, ex);}


1 1
原创粉丝点击