12、Properties文件操作
Properties(java.util.Properties)主要用于读取java的配置文件,各种语言都有自己所支配的配置文件,配置文件中很多变量是经常改变的,这样做也是为了方便用户,让用户能够脱离程序本身去修改相关的变量设置
它提供了几种主要方法
1、getProperties(Sreing key),用指定的键在此属性列表中搜索属性,也就是通过参数key,得到key所对应的value。
2、**load(InputStream InStream),**从输入流中读取属性列表。通过对指定文件进行装载来获取文件中的所有键、值。以提供getProperty(String key)来搜索。
3、setProperty ( String key, String value),调用Hashtable的方法put。他通过调用基类的put方法来设置 键-值对。
4、**store ( OutputStream out, String comments),**以适合使用 load方法加载到 Properties表中的格式,将此Properties表中的属性列表(键和元素对)写入输出流。与load方法相反,该方法将键-值对写入到指定的文件中去。
5、**clear(),**清除所有装载的键-值对。该方法在基类中提供。
package IO;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;
/*
* properties可以用来配置文件
* javaweb、javaee开发中通常会用到
*
* ResouceBundle只读
* peoperties可读可写
*
*/
public class PropertiesDemo {
public static String version="";
public static String username="";
public static String password="";
//静态代码块,只执行一次
static {
//readConfig();
}
/*
* 对属性文件的写入操作
*/
private static void writeConfig(String version,String username,String password) {
Properties p=new Properties();
p.put("app.version", version);
p.put("db.username", username);
p.put("db.password", password);
try {
//OutputStream out=new FileOutputStream("config.properties");
OutputStream out=new FileOutputStream("config.properties");
//写文件
p.store(out, "update config");
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/*
* 对属性文件的读取操作
* 读取Properties配置文件
*/
private static void readConfig() {
Properties p=new Properties();
try {
//配置文件在同一个包里,通过当前线程的类的加载器对象,来加载指定包下的配置文件
//InputStream in=Thread.currentThread().getContextClassLoader().
// getResourceAsStream("IO/config.properties");
//配置文件在同一个目录下
InputStream in=new FileInputStream("config.properties");
p.load(in);//加载文件
//从properties中获取文件
version=p.getProperty("aap.version");
username=p.getProperty("db.usersion");
password=p.getProperty("db.password");
in.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
//writeConfig("2", "vines", "120948");
readConfig();
System.out.println(PropertiesDemo.version);
System.out.println(PropertiesDemo.username);
System.out.println(PropertiesDemo.password);
}
}
执行readConfig();
1
jhjh
1324
执行writeConfig(“2”, “vines”, “120948”);