Properties ----》 配置文件類 屬于Map集合體系的。
Properties的作用:
- 生成配置文件蛀柴。
- 讀取配置郭卫。
Properties要注意的事項(xiàng):
- 往Properties添加數(shù)據(jù)的時(shí)候比然,千萬不要添加非字符串類型的數(shù)據(jù)囤攀,如果添加了非字符串類型的數(shù)據(jù)软免,那么properties的處理方式就是進(jìn)行強(qiáng)制類型轉(zhuǎn)換,強(qiáng)轉(zhuǎn)報(bào)錯(cuò)焚挠。
- 如果properties的數(shù)據(jù)出現(xiàn)了中文字符膏萧,那么使用store方法時(shí),千萬不要使用字節(jié)流蝌衔,如果使用了字節(jié)流榛泛,那么默認(rèn)使用iso8859-1碼表進(jìn)行保存,如果出了中文數(shù)據(jù)建議使用字符流噩斟。
- 如果修改了properties里面 的數(shù)據(jù)挟鸠,一定要重新生成一個(gè)配置文件。
package cn.itcast.other;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Set;
public class Demo4 {
public static void main(String[] args) throws IOException {
// createProperties();
readProperties();
}
//讀取配置文件 ---- 加載配置文件到Properties是使用load方法亩冬。
public static void readProperties() throws IOException{
//創(chuàng)建一個(gè)Properties
Properties properties = new Properties();
//建立輸入字符流對(duì)象
FileReader fileReader = new FileReader("f:\\users.properties");
//加載配置文件的數(shù)據(jù)到Properties是使用load方法。
properties.load(fileReader);
//遍歷元素
Set<Entry<Object, Object>> set = properties.entrySet();
for(Entry<Object, Object> entry: set){
System.out.println("鍵:"+ entry.getKey()+" 值:"+ entry.getValue());
}
//修改狗娃...
properties.setProperty("狗娃", "110");
//重新生成一個(gè)配置文件
properties.store(new FileWriter("f:\\users.properties"), "hehe");
}
//創(chuàng)建一個(gè)配置文件
public static void createProperties() throws IOException{
//創(chuàng)建一個(gè)Properties對(duì)象
Properties properties = new Properties();
properties.setProperty("狗娃", "123");
properties.setProperty("狗剩", "234");
properties.setProperty("鐵蛋", "456");
//FileOutputStream fileOutputStream = new FileOutputStream("f:\\users.properties");
FileWriter fileWriter = new FileWriter("f:\\users.properties");
//利用Properties生成一個(gè)配置文件硼身。
properties.store(fileWriter, "hehe"); //第二個(gè)參數(shù)是使用一段文字對(duì)參數(shù)列表進(jìn)行描述硅急。
}
}
Paste_Image.png
Properties實(shí)戰(zhàn)
需求:
使用porperites文件實(shí)現(xiàn)本軟件只能試用三次,三次之后提示用戶購(gòu)買正版佳遂,退出jvm营袜。
public class Demo5 {
public static void main(String[] args) throws IOException {
//先檢查是否存在配置文件
File file = new File("F:\\runtime.properties");
if(!file.exists()){//,如果不存在丑罪,創(chuàng)建配置文件
file.createNewFile();
}
//創(chuàng)建一個(gè)Properties對(duì)象
Properties properties = new Properties();
//加載配置文件
properties.load(new FileReader(file));
//定義一個(gè)變量記錄運(yùn)行的次數(shù)
int count = 0;
//如果配置文件記錄了運(yùn)行次數(shù)荚板,則應(yīng)該使用配置文件的運(yùn)行次數(shù)
String num = properties.getProperty("num");
if(num!=null){
count = Integer.parseInt(num);
}
//判斷是否已經(jīng)運(yùn)行了三次
if(count==3){
System.out.println("已經(jīng)到了使用次數(shù),請(qǐng)購(gòu)買正版7砸佟跪另!88");
System.exit(0);
}
count++;
properties.setProperty("num", count+"");
System.out.println("你已經(jīng)運(yùn)行了"+count+"次,還剩余"+(3-count)+"次");
//重新生成配置文件
properties.store(new FileWriter(file), "runtime");
}
}