Properties文件操作
Properties(Java.util.Properties),主要用于读取Java的配置文件,
各种语言都有自己所支持的配置文件,配置文件中很多变量是经常改变的,
这样做也是为了方便用户,让用户能够脱离程序本身去修改相关的变量设置。
它提供了几个主要的方法:
1、getProperty ( String key),用指定的键在此属性列表中搜索属性。也就是通过参数 key ,得到 key 所对应的 value。
2、 load ( InputStream inStream),从输入流中读取属性列表(键和元素对)。
通过对指定的文件(比如说上面的 test.properties 文件)进行装载来获取该文件中的所有键 - 值对。
以供 getProperty ( String key) 来搜索。
3、setProperty ( String key, String value) ,调用 Hashtable 的方法 put 。他通过调用基类的put方法来设置 键 - 值对。
4、store ( OutputStream out, String comments),以适合使用 load 方法加载到 Properties 表中的格式,
将此 Properties 表中的属性列表(键和元素对)写入输出流。
与 load 方法相反,该方法将键 - 值对写入到指定的文件中去。
5、 clear (),清除所有装载的 键 - 值对。该方法在基类中提供。
- Properties:
- properties可以用来做配置文件
- javaweb javaee 开发中通常会用到
- ResouceBundle 只读
- Properties 可读可写
package com.vince;
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:
* properties可以用来做配置文件
* javaweb javaee 开发中通常会用到
*
* ResouceBundle 只读
* Properties 可读可写
*
* @author vince
* @description
*/
public class PropertiesDemo {
public static String version = "";
public static String username = "";
public static String password = "";
//静态代码块,只会执行一次
static{
//readConfig();
}
/**
* 对属性文件的写操作
* @param version
* @param username
* @param password
*/
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");
//写文件
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 inStream = Thread.currentThread().getContextClassLoader()
.getResourceAsStream("com/res/config.properties");
// InputStream inStream = new FileInputStream("config.properties");
p.load(inStream);//加载文件
//从properties中获取数据
version = p.getProperty("app.version");
username = p.getProperty("db.username");
password = p.getProperty("db.password");
inStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
//writeConfig("2","vince","654321");
readConfig();
System.out.println(PropertiesDemo.version);
System.out.println(PropertiesDemo.username);
System.out.println(PropertiesDemo.password);
}
}
这样的话直接在工程目录下 路径可以直接写名字
但若在某个package包下
就要这样写
利用线程的 上下文类加载器getContextClassLoader()
加载进内存后 创建流 getResourceAsStream出来()
类加载器既然能加载类 也能加载资源文件
//通过当前线程的类加载器对象,来加载指定包下的配置文件
InputStream inStream = Thread.currentThread().getContextClassLoader()
.getResourceAsStream("com/res/config.properties");