Java工具类——Properties类--简单使用

一、什么是Properties类

1. Properties 类位于 java.util.Properties ,是Java 语言的配置文件所使用的类, Xxx.properties 为Java 语言常见的配置文件,如数据库的配置 jdbc.properties, 系统参数配置 system.properties。 
2. 以key=value 的 键值对的形式进行存储值。 key值不能重复
3. 文件中,可以用"#"来作注释,properties文件在Java编程中用到的地方很多,操作很方便

二、Properties常用方法

1.setProperty(String key,String value)
调用HashTable的方法put。

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

3.getProperty(String key, String defaultValue)
用指定的键在属性列表中搜索属性。

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

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

6.loadFromXML(InputStream in)
将指定输入流中由 XML 文档所表示的所有属性加载到此属性表中。

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

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

9.storeToXML(OutputStream os, String comment)
发出一个表示此表中包含的所有属性的 XML 文档。

10.storeToXML(OutputStream os, String comment, String encoding)
使用指定的编码发出一个表示此表中包含的所有属性的 XML 文档。

11.clear (),清除所有装载的 键 - 值对。该方法在基类中提供。
在这里插入图片描述

三、方法演示

1. 为properties对象添加属性和获取值

@Test
    public void setAndGetProperty() {
    
    
      Properties pro=new Properties();
     //设置值
      pro.setProperty("driver", "com.mysql.jdbc.Driver");
      pro.setProperty("url", "jdbc:mysql///user");
      pro.setProperty("user", "root");
      pro.setProperty("password", "451535");
      //获取值:
      //1、getProperty(String key)方法  通过键获取值
      String str1= pro.getProperty("driver");
      System.out.println(str1); //正常获取-->  com.mysql.jdbc.Driver
      //2、getProperty(String key, String defaultValue)重载方法
      //当properties对象中没有所指定的键值时,显示给定的默认值
      String str2=pro.getProperty("driver", "没有该值");
      String str3=pro.getProperty("haha", "没有该值");
      System.out.println(str2);//对象中有driver  则会输出设置进去的 -->com.mysql.jdbc.Driver
      System.out.println(str3);//对象中没有这个键,则会输出默认值 -->没有该值
  }

2. 输出properties的内容

 public static void main(String[] args) throws Exception {
    
    
        //    ./当前路径  ---》file.getAbsolutePath() 获取当前文件的路径
        File file = new File("src/Properties/FileinputStream/one.properties");
        //   System.out.println(file.exists());//判断文件是否存在
        //创建一个文件输入流
        FileInputStream fileInputStream = new FileInputStream(file);
        //调用properties类
        Properties properties = new Properties();
        //把流对象传进去
        properties.load(fileInputStream);
        //关闭流对象
        fileInputStream.close();
        //使用枚举器(只能用于Hashtable   Vector) 输出properties内的内容  ---与迭代器同理
        Enumeration<Object> keys = properties.keys();
        while (keys.hasMoreElements()){
    
    
        //获取key的值  并强转成String
            String o =(String) keys.nextElement();
        //调用get方法  获取value 值
            System.out.println(o+"="+properties.get(o));
        }
    }

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

public static void main(String[] args) throws IOException {
    
    
		// TODO Auto-generated method stub
            write();
	}
	
private static void write() throws IOException {
    
    
	Properties prop =new Properties();
	//添加
	prop.setProperty("张三","13");
	prop.setProperty("李四","14");
	prop.setProperty("王五","15");
	//获取输出流字节
	OutputStream fw =new FileOutputStream("config3.properties");
	//字符流转化为字节流
	OutputStreamWriter fos =new OutputStreamWriter(fw,"utf-8");
	prop.store(fos,"这是三个人的信息");
	//关流
	fos.close();

4. 模仿下Properties类的load()和store()方法

public class MyProperties {
    
    
	private Hashtable<String,String> table;
	
    public MyProperties() {
    
    
    	table = new Hashtable<String,String>();
    }
    public void setProperty(String key,String value) {
    
    
    	table.put(key,value);
    }
    public String getProperty(String key) {
    
    
    	return table.get(key);
    }
    //模仿Property的load方法
    public void load(InputStream is) throws IOException {
    
    
    BufferedReader bfr =new BufferedReader(new InputStreamReader(is,"utf-8"));
    String line = null;
    while((line=bfr.readLine())!=null) {
    
    
    	//字符串的截取  	
    	String [] bg = line.split("=");   
    	table.put(bg[0],bg[1]);    	
    }
    }    
    //模仿Property的store方法
    public void store(OutputStream os) throws IOException {
    
    
    Set<String>  sets =table.keySet();
    BufferedWriter bw =new BufferedWriter(new OutputStreamWriter(os,"gbk"));
    for(String Key:sets) {
    
    
    	String item =Key+"="+table.get(Key);
    	bw.write(item);
    	bw.newLine();
    	bw.flush();
    }
    bw.close();
    }
}

四、案例

1. 需求:这个程序只能最多执行5次 超多5次后 提醒用户交钱

public static void main(String[] args) throws FileNotFoundException, IOException {
    
    
	    //需要用到Properties类
		Properties prop =new Properties();
	   //从count.txt中读取数据
		prop.load(new InputStreamReader(new FileInputStream("count.txt")));
		//获取value并且进行String-int转换
		while(true) {
    
    
			int count = Integer.parseInt(prop.getProperty("count"));
			if(count>=5) {
    
    
				System.out.println("使用次数已经用完,请充值");
				break;
			}
			System.out.println("程序正常运行");
			count++;
			//int和字符拼接等于String
			prop.setProperty("count",count+"");
		}
		prop.store(new OutputStreamWriter(new FileOutputStream("resercount.txt"))," ");						
	}

2.如何将文件保存到属性文件中?

import java.util.*;
import java.io.*;

public class StoreXML {
    
    
  public static void main(String args[]) throws Exception {
    
    
    Properties prop = new Properties();
    prop.setProperty("one-two", "buckle my shoe");
    prop.setProperty("three-four", "shut the door");
    prop.setProperty("five-six", "pick up sticks");
    prop.setProperty("seven-eight", "lay them straight");
    prop.setProperty("nine-ten", "a big, fat hen");
    prop.storeToXML(new FileOutputStream("test.xml"), "saveXML");//将键值对儿保存到XML文件中
prop.store(new FileOutputStream("test.properties"), "saveProperties");//将键值对儿保存到普通的属性文件中
    fos.close();
  }
}

将键值对儿保存到XML文件中的输出结果如下:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties>
<comment>Rhyme</comment>
<entry key="seven-eight">lay them straight</entry>
<entry key="five-six">pick up sticks</entry>
<entry key="nine-ten">a big, fat hen</entry>
<entry key="three-four">shut the door</entry>
<entry key="one-two">buckle my shoe</entry>
</properties>

五、Properties获取数据乱码解决

1.原因
Properties调用load(InputStream)时,读取文件时使用的默认编码为ISO- 8859-1;当 我们将中文放入到properties文件中,通过getProperty(key)获取值时,取到得数据是ISO-8859-1格式的,但是ISO-8859-1是不能识别中文的。

2.解决方法
通过getProperty()获取的数据data既然是ISO-8859-1编码的,就通过data.getByte(“iso-8859-1”)获取获取,使用new String(data.getByte(“iso-8859-1”),”UTF-8”)进行转换。当然properties文件的编码类型需要和new String(Byte[],charset)中的第二个参数的编码类型相同。

猜你喜欢

转载自blog.csdn.net/haobo__/article/details/109693130