黑马程序员--java基础之类集框架(四)
Properties类
1、是tableMap的子类,具有Map的特点,而且里面存储的都是字符串类型的键值对;
2、是集合和IO流相结合的集合容器;
3、该对象用于键值对形式的配置文件;
练习一:将流中的数据存储到集合中进行操作;例,将一个文本文档info.txt中的配置信息存到集合中
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
|
import java.io.*;import java.util.*;class PropertiesTest{ public static void main(String [] args) throws IOException{ //method_1(); Properties pro = new Properties(); FileInputStream fis = new FileInputStream("info.txt"); pro.load(fis);//将流中的信息加载到容器中 pro.list(System.out);//将容器中的输出到输出流中 //System.out.println(pro); } public static void method_1()//该方法其实是load方法的原理,实际开发中只需要调用load方法就可以 { Properties pro = new Properties(); BufferedReader br = null; try { br = new BufferedReader(new FileReader("info.txt")); String line = null; while((line = br.readLine())!=null){ String [] arr = line.split("="); pro.setProperty(arr[0], arr[1]); } System.out.println(pro); } catch(IOException e) { System.out.println(e.toString()); } finally{ try { br.close(); } catch(IOException e) { System.out.println(e.toString()); } } }} |
练习二:记录程序的运行次数,达到一定次数后显示提示信息
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
|
class PropertiesTest{ public static void main(String [] args) throws IOException{ Properties pro = new Properties(); File file = new File("info.ini");//将文件进行封装,避免抛异常 if(!file.exists()) file.createNewFile(); FileInputStream fis = new FileInputStream(file); pro.load(fis); String value = pro.getProperty("time"); int count = 0; if(value != null) count = Integer.parseInt(value); if(count >= 5){ System.out.println("试用次数已到,请注册正式版本"); return; } count++; pro.setProperty("time", count+""); FileOutputStream fos = new FileOutputStream(file); pro.store(fos,"zhushi"); fis.close(); fos.close(); } } |

浙公网安备 33010602011771号