Java Properties
学过但是又忘了的知识,最近读配置文件发现很有用,希望通过博客记录下来,以便以后复习!
一、Java Properties类
位置:Java.util.Properties
主要用于读取Java的配置文件,在Java中,其配置文件常为.properties文件,格式为文本文件,文件的内容的格式是“键=值”的格式,文本注释信息可以用"#"来注释。
类结构:
二、常用方法
1. getProperty ( String key),用指定的键在此属性列表中搜索属性。
2. load ( InputStream inStream),从输入流中读取属性列表(键和元素对)。
3. setProperty ( String key, String value) ,调用 Hashtable 的方法 put 。
4. store ( OutputStream out, String comments),以适合使用 load 方法加载到 Properties 表中的格式,将此 Properties 表中的属性列表(键和元素对)写入输出字符。
三、读取的6种方法
1。使用java.util.Properties类的load()方法
示例: InputStream in = lnew 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()所得到的java.lang.ClassLoader的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);
补充
Servlet中可以使用javax.servlet.ServletContext的getResourceAsStream()方法
示例:InputStream in = context.getResourceAsStream(path);
Properties p = new Properties();
p.load(in);
转自-----http://blog.youkuaiyun.com/Senton/article/details/4083127
四、properties读取jdbc配置文件
配置文件内容:
url=jdbc\:mysql\://localhost\:3306/test
driverClass=com.mysql.jdbc.Driver
username=root
password=zyp
package day0919.two;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
public class DbUtils {
static Properties p = new Properties();
/**
* 初始化读取jdbc的参数
* */
static{
//'/'代表根目录读取
InputStream is = DbUtils.class.getResourceAsStream("jdbc.properties");
try {
p.load(is);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 获取Connection的方法
* */
public static Connection getConn() {
//获取url
String url = p.getProperty("url");
//获取驱动类
String driverClass = p.getProperty("driverClass");
//获取用户名
String username = p.getProperty("username");
//获取密码
String password = p.getProperty("password");
Connection conn=null;
try {
//加载驱动类
Class.forName(driverClass);
//获取Connection
conn=DriverManager.getConnection(url, username, password);
} catch (SQLException e) {
e.printStackTrace();
}catch (ClassNotFoundException e) {
e.printStackTrace();
}
//返回Connection
return conn;
}
}