码迷,mamicode.com
首页 > 其他好文 > 详细

配置文件类 Properties

时间:2017-01-05 22:36:32      阅读:187      评论:0      收藏:0      [点我收藏+]

标签:table   exists   元素   iso   src   creat   comment   start   继承   

Properties(配置文件类): 主要用于生产配置文件与读取配置文件的信息。

Properties属于集合类,继承于Hashtable。

Properties要注意的细节:
    1. 如果配置文件的信息一旦使用了中文,那么在使用store方法生成配置文件的时候只能使用字符流解决,如果使用字节流生成配置文件的话,默认使用的是iso8859-1码表进行编码存储,这时候会出现乱码。
    2. 如果Properties中的内容发生了变化,一定要重新使用Properties生成配置文件,否则配置文件信息不会发生变化。

常用方法:

1、构造方法:

Properties() 创建一个无默认值的空属性列表。

Properties(Properties defaults) 创建一个带有指定默认值的空属性列表。

2、常用方法

void load(InputStream inStream) 从输入流中读取属性列表(键和元素对)。

void load(Reader reader) 按简单的面向行的格式从输入字符流中读取属性列表(键和元素对)。

void  store(OutputStream out, String comments) 以适合使用 load(InputStream) 方法加载到 Properties 表中的格式,将此 Properties 表中的属性列表(键和元素对)写入输出流。

void  store(Writer writer, String comments) 以适合使用 load(Reader) 方法的格式,将此 Properties 表中的属性列表(键和元素对)写入输出字符。

Object setProperty(String key, String value) 调用 Hashtable 的方法 put

String getProperty(String key) 用指定的键在此属性列表中搜索属性。

实战:使用properties实现本软件只能 运行三次,超过了三次之后就提示购买正版并推出jvm。

代码示例如下

技术分享
 1 import java.io.File;
 2 import java.io.FileReader;
 3 import java.io.FileWriter;
 4 import java.io.IOException;
 5 import java.util.Properties;
 6 
 7 
 8 public class DemoProperties {
 9     
10     public static void main(String[] args) throws IOException {
11         File file = new File("E:\\nick.property");
12         if (!file.exists()) {
13             file.createNewFile();
14         }
15         Properties properties = new Properties();
16         properties.load(new FileReader(file));
17         int count = 0;
18         String value = properties.getProperty("登录次数");
19         if (value!=null ) {
20             count = Integer.parseInt(value);
21         }
22         count++;
23         if (count>=3) {
24             System.out.println("试用期已过,请购买正版。");
25             System.exit(0);
26         }
27         
28         properties.setProperty("登录次数", count+"");
29         properties.store(new FileWriter(file), "登录次数"+count);
30     }
31 
32 }
View Code

 

配置文件类 Properties

标签:table   exists   元素   iso   src   creat   comment   start   继承   

原文地址:http://www.cnblogs.com/nicker/p/6253536.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!