------- android培训、java培训、期待与您交流! ----------
Properties对象时hashtable的子类
具备Map集合的特点,里面存储的键值对都是字符串
是集合中和IO技术相结合的集合容器
该对象的特点,可以由于键值对形式的配置文件.
那么在加载数据时,需要数据有固定格式,通常就是键对应值
对照API尝试使用一些常用的方法
package com.File;
import java.io.*;
import java.util.*;
public class PropertiesDemo
{
public static void main(String[] args)throws IOException
{
//setAndGet();
method_1();
}
//设置和获取元素
public static void setAndGet()
{
Properties prop = new Properties();
prop.setProperty("zhangsan", "30");
prop.setProperty("lisi","39");
//打印几个和中的元素
System.out.println(prop);
//getProperty能够根据返元素key返回所对应的value字符串
String value = prop.getProperty("lisi");
System.out.println(value);
//遍历循环中所有的元素,stringPropertyName可以返回一个set集合
Set<String> names = prop.stringPropertyNames();
//Set集合遍历的方式有很多种,我们可以用高级for循环
for(String name : names)
{
System.out.println(name+":::::::"+prop.getProperty(name));
}
}
//演示:如何将流中的数据存储到集合中
//想要将一个文本中的键值数据存储到集合中进行操作
/*
1.用一个流和目标文件管理
2.读取一行数据,将这行数据用=切割
3.等号左边是key,右面是value,存入到Property集合中即可
*/
public static void method_1()throws IOException
{
BufferedReader br = new BufferedReader(new FileReader("f:\\java\\java\\2.txt"));
String line = null;
Properties prop = new Properties();
while((line=br.readLine())!=null)
{
String []arr = line.split("=");
System.out.println(arr[0]+"::::"+arr[1]);
prop.setProperty(arr[0], arr[1]);
}
br.close();
System.out.println(prop);
}
public static void loadDemo()throws IOException
{
Properties prop = new Properties();
FileInputStream fis = new FileInputStream("f:\\java\\java\\2.txt");
//将六种的数据加载进集合
prop.load(fis);
prop.setProperty("wangwu","30");
FileOutputStream fos = new FileOutputStream("f:\\java\\java\\2.txt");
prop.store(fos, "wawa");
//System.out.println(prop);
prop.list(System.out);
fos.close();
fis.close();
}
}
在网上了解到properties通常用的集中读取文件方式
1。使用java.util.Properties类的load()方法
InputStream in = new BufferedInputStream(new FileInputStream(name));
Properties p = new Properties();
p.load(in);
2。使用java.util.ResourceBundle类的getBundle()方法
ResourceBundle rb = ResourceBundle.getBundle(name, Locale.getDefault());
3。使用java.util.PropertyResourceBundle类的构造函数
InputStream in = new BufferedInputStream(new FileInputStream(name));
ResourceBundle rb = new PropertyResourceBundle(in);
4。使用class变量的getResourceAsStream()方法
InputStream in = JProperties.class.getResourceAsStream(name);
Properties p = new Properties();
p.load(in);
5。使用class.getClassLoader()的getResourceAsStream()方法
InputStream in = JProperties.class.getClassLoader().getResourceAsStream(name);
Properties p = new Properties();
p.load(in);
6。使用java.lang.ClassLoader类的getSystemResourceAsStream()静态方法
InputStream in = ClassLoader.getSystemResourceAsStream(name);
Properties p = new Properties();
p.load(in);