社区微信群开通啦,扫一扫抢先加入社区官方微信群
社区微信群
Java中有个比较重要的类Properties(Java.util.Properties),主要用于读取Java的配置文件,
格式为文本文件,文件的内容的格式是“键=值”的格式,文本注释信息可以用"#"来注释。
Properties类继承自Hashtable,如下:
它提供的方法有:
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 方法相反,该方法将键 - 值对写入到指定的文件中去。
使用J2SE API读取Properties文件的六种方法
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);
DBconfig.properties文件
#这是注释
driverClassName=oracle.jdbc.driver.OracleDriver
url=jdbc:oracle:thin:@127.0.0.1:1521:orcl
userName=scott
passWord=tigger
一. 普通JAVA Project ,读取.properties文件
将.properties文件放在项目的根目录下面即可。
代码如下:
public Connection getConnection(){
Properties prop=new Properties();
Connection conn=null;
try {
prop.load(this.getClass().getClassLoader()
.getResourceAsStream("DBconfig.properties"));
String driver=prop.getProperty("driverClassName");
String url=prop.getProperty("url");
String username=prop.getProperty("userName");
String password=prop.getProperty("passWord");
Class.forName(driver);
conn= DriverManager.getConnection(url, username, password);
} catch (Exception e) {
e.printStackTrace();
}
return conn;
}
二. servlet中读取.properties文件
须将.properties文件放在WebContent目录下。
代码如下:
Properties properties = new Properties() ;
try {
FileInputStream fileInputStream = new FileInputStream(
new File(request.getRealPath("")+ "/" + "DBconfig.properties"));
properties.load(fileInputStream) ;
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
}
如果觉得我的文章对您有用,请随意打赏。你的支持将鼓励我继续创作!