Properties ----》 配置文件類 屬于Map集合體系的。
Properties的作用:
- 生成配置文件。
- 讀取配置。
Properties要注意的事項:
- 往Properties添加數據的時候,千萬不要添加非字符串類型的數據,如果添加了非字符串類型的數據,那么properties的處理方式就是進行強制類型轉換,強轉報錯。
- 如果properties的數據出現了中文字符,那么使用store方法時,千萬不要使用字節流,如果使用了字節流,那么默認使用iso8859-1碼表進行保存,如果出了中文數據建議使用字符流。
- 如果修改了properties里面 的數據,一定要重新生成一個配置文件。
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{
//創建一個Properties
Properties properties = new Properties();
//建立輸入字符流對象
FileReader fileReader = new FileReader("f:\\users.properties");
//加載配置文件的數據到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");
//重新生成一個配置文件
properties.store(new FileWriter("f:\\users.properties"), "hehe");
}
//創建一個配置文件
public static void createProperties() throws IOException{
//創建一個Properties對象
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生成一個配置文件。
properties.store(fileWriter, "hehe"); //第二個參數是使用一段文字對參數列表進行描述。
}
}
Paste_Image.png
Properties實戰
需求:
使用porperites文件實現本軟件只能試用三次,三次之后提示用戶購買正版,退出jvm。
public class Demo5 {
public static void main(String[] args) throws IOException {
//先檢查是否存在配置文件
File file = new File("F:\\runtime.properties");
if(!file.exists()){//,如果不存在,創建配置文件
file.createNewFile();
}
//創建一個Properties對象
Properties properties = new Properties();
//加載配置文件
properties.load(new FileReader(file));
//定義一個變量記錄運行的次數
int count = 0;
//如果配置文件記錄了運行次數,則應該使用配置文件的運行次數
String num = properties.getProperty("num");
if(num!=null){
count = Integer.parseInt(num);
}
//判斷是否已經運行了三次
if(count==3){
System.out.println("已經到了使用次數,請購買正版!!88");
System.exit(0);
}
count++;
properties.setProperty("num", count+"");
System.out.println("你已經運行了"+count+"次,還剩余"+(3-count)+"次");
//重新生成配置文件
properties.store(new FileWriter(file), "runtime");
}
}