java中Properties类的使用,网上文章整理
来源:互联网 发布:js中为div添加点击事件 编辑:程序博客网 时间:2024/06/07 06:51
package com.adrop.util;
import java.io.*;
import java.util.properties;
import javax.servlet.http.*;
import javax.servlet.*;
import javax.servlet.jsp.*;
public class propertiesutil {
private string filename;
private properties p;
private fileinputstream in;
private fileoutputstream out;
/**
* 根据传进的文件名载入文件
* @param filename string
*/
public propertiesutil(string filename) {
this.filename=filename;
file file = new file(filename);
try {
in = new fileinputstream(file);
p = new properties();
//载入文件
p.load(in);
in.close();
}
catch (filenotfoundexception e) {
system.err.println("设置文件config.properties未找到!!");
e.printstacktrace();
}
catch (exception e) {
system.err.println("读取设置文件config.properties错误!!");
e.printstacktrace();
}
}
/**
* 设置文件一律为config.propertities,并且统一放在web应用的根目录下。
* @return string
*/
public static string getconfigfile(httpservlet hs) {
return getconfigfile(hs,"config.properties");
}
/**
* 在servlet中使用,直接用this作为参数,httpservlet类型
* 根据设置文件名从当前web应用的根目录下找出设置文件
* @param hs httpservlet
* @param configfilename string设置文件名字
* @return string
*/
public static string getconfigfile(httpservlet hs, string configfilename) {
string configfile = "";
servletcontext sc = hs.getservletcontext();
configfile = sc.getrealpath("/" + configfilename);
if (configfile == null || configfile.equals("")) {
configfile = "/" + configfilename;
}
return configfile;
}
/**
* jsp中用pagecontext作参数
* @param hs pagecontext
* @param configfilename string 设置文件名字
* @return string
*/
public static string getconfigfile(pagecontext hs, string configfilename) {
string configfile = "";
servletcontext sc = hs.getservletcontext();
configfile = sc.getrealpath("/" + configfilename);
if (configfile == null || configfile.equals("")) {
configfile = "/" + configfilename;
}
return configfile;
}
/**
* 列出所有的设置文件内容
*/
public void list() {
p.list(system.out);
}
/**
* 指定设置项名称,返回设置值
* @param itemname string
* @return string
*/
public string getvalue(string itemname){
return p.getproperty(itemname);
}
/**
* 指定设置项名称和默认值,返回设置值
* @param itemname string
* @param defaultvalue string
* @return string
*/
public string getvalue(string itemname,
string defaultvalue){
return p.getproperty(itemname,defaultvalue);
}
/**
* 设置设置项名称及其值
* @param itemname string
* @param value string
*/
public void setvalue(string itemname,string value){
p.setproperty(itemname,value);
return;
}
/**
* 保存设置文件,指定文件名和抬头描述
* @param filename string
* @param description string
* @throws exception
*/
public void savefile(string filename,string description)throws exception{
try {
file f=new file(filename);
out
= new fileoutputstream(f);
p.store(out, description);//保存文件
out.close();
}
catch (ioexception ex) {
throw new exception
("无法保存指定的设置文件:"+filename);
}
}
/**
* 保存设置文件,指定文件名
* @param filename string
* @throws exception
*/
public void savefile(string filename)
throws exception {
savefile(filename,"");
}
/**
* 保存设置文件,采用原文件名
* @throws exception
*/
public void savefile() throws exception {
if(filename.length()==0)
throw new exception
("需指定保存的设置文件名");
savefile(filename);
}
/**
* 删除一个属性
* @param value string
*/
public void deletevalue(string value){
p.remove(value);
}
/**
* main method for test
* @param args string[]
*/
public static void main(string[] args) {
string file = "f:\\p.properties";
propertiesutil pu = new propertiesutil(file);
pu.list();
}
}
一个既能读又写入dbConfig.properties(数据库配置文件)java源代码
答案一
public class ConnectionHelper {
/**
* 通过JNDI获取数据源
*/
private static DataSource getDataSource(){
//建立JNDI的上下文
try {
InitialContext ct = new InitialContext();
DataSource source = (DataSource)ct.lookup("java:/comp/env/jdbc/shop");
return source;
} catch (Exception e) {
throw new RuntimeException("获取数据源失败",e);
}
}
//从Properties文件加载配置参数
public static Properties getConfig(){
Properties pro = new Properties();
InputStream is = ConnectionHelper.class.getResourceAsStream("/com/lxw/config/db.properties");
try {
pro.load(is);
return pro;
} catch (IOException e) {
throw new DBException("加载配置文件失败",e);
}
}
private static DataSource ds = null;
//自构建数据源
public static synchronized DataSource getMyDataSource(){
if(ds == null){
Properties pro = getConfig();
BasicDataSource bdc = new BasicDataSource();
bdc.setDriverClassName(pro.getProperty("dbDriver"));
bdc.setUrl(pro.getProperty("dbUrl"));
bdc.setUsername(pro.getProperty("dbUser"));
bdc.setPassword(pro.getProperty("dbPassword"));
String num = pro.getProperty("dbMaxActive");
if(num != null && num.equals("")){
bdc.setMaxActive(Integer.parseInt(num));
}
/*bdc.setDriverClassName("com.mysql.jdbc.Driver");
bdc.setUrl("jdbc:mysql://localhost:3306/shop");
bdc.setUsername("root");
bdc.setPassword("123");
bdc.setMaxActive(20);*/
ds = bdc;
}
return ds;
}
//获取统一的数据库连接
public static Connection getCon(){
try {
//return getDataSource().getConnection();
//通过自构建的数据源获取连接
return getMyDataSource().getConnection();
} catch (SQLException e) {
throw new DBException("获取数据库连接失败",e);
}
}
//关闭连接
public static void closeCon(Connection con){
try {
if(null != con && !con.isClosed()){
con.close();
con = null;
}
} catch (SQLException e) {
throw new DBException("关闭数据库连接失败",e);
}
}
public static void main(String[] args) {
System.out.println(getCon());
System.out.println("获取连接成功");
}
}
答案二
/**
* 读取属性文件
* <p>Title: </p>
* <p>Description: </p>
* <p>Copyright: Copyright (c) 2005</p>
* <p>Company: </p>
* @author zhanggy
* @version 1.0
*/
public class PropertyManager {
private static PropertyManager manager = null;
private static Object managerLock = new Object();
/**
* Returns a Jive property.
*
* @param name the name of the property to return.
* @return the property value specified by name.
*/
public static String getProperty(String propsName,String name) {
if (manager == null) {
synchronized(managerLock) {
if (manager == null) {
manager = new PropertyManager(propsName);
}
}
}
return manager.getProp(name);
}
private Properties properties = null;
private Object propertiesLock = new Object();
private String resourceURI;
/**
* Creates a new PropertyManager. Singleton access only.
*/
private PropertyManager(String resourceURI) {
this.resourceURI = resourceURI;
}
/**
* Gets a Jive property. Jive properties are stored in jive.properties.
* The properties file should be accesible from the classpath. Additionally,
* it should have a path field that gives the full path to where the
* file is located. Getting properties is a fast operation.
*
* @param name the name of the property to get.
* @return the property specified by name.
*/
protected String getProp(String name) {
//If properties aren't loaded yet. We also need to make this thread
//safe, so synchronize...
if (properties == null) {
synchronized(propertiesLock) {
//Need an additional check
if (properties == null) {
loadProps();
}
}
}
String property = properties.getProperty(name);
if (property == null) {
return null;
}
else {
return property.trim();
}
}
/**
* Loads Jive properties from the disk.
*/
private void loadProps() {
properties = new Properties();
InputStream in = null;
try {
in = getClass().getResourceAsStream(resourceURI);
properties.load(in);
in.close();
}
catch (Exception e) {
System.err.println("Error reading properties in PropertyManager.loadProps() " + e);
e.printStackTrace();
}
finally {
try {
in.close();
} catch (Exception e) { }
}
}
// public static void main(String[] args) {
// String dbtype = PropertyManager.getProperty("/dbconfig.properties", "dbtype");
// System.out.println("dbtype = "+dbtype);
// }
}
java获取properties配置文件
package test.bwl;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class Test {
private static Properties properties = new Properties();
public static void main(String[] args) {
try {
InputStream is = Test.class.getClassLoader().getResourceAsStream("cache.properties");
properties.load(is);
String size = properties.getProperty("cache.size");
writeLog("配置成功!" + size);
} catch (FileNotFoundException e) {
writeLog("配置文件不存在!" + e.getMessage());
} catch (IOException e) {
writeLog("读取配置文件IO错误!" + e.getMessage());
}
}
public static void writeLog(String strLog) {
System.out.println(strLog);
}
}
package test.bwl;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class Test {
private static Properties properties = new Properties();
public static void main(String[] args) {
try {
InputStream is = Test.class.getClassLoader().getResourceAsStream("cache.properties");
properties.load(is);
String size = properties.getProperty("cache.size");
writeLog("配置成功!" + size);
} catch (FileNotFoundException e) {
writeLog("配置文件不存在!" + e.getMessage());
} catch (IOException e) {
writeLog("读取配置文件IO错误!" + e.getMessage());
}
}
public static void writeLog(String strLog) {
System.out.println(strLog);
}
}
package test.bwl;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.regex.Pattern;
/**
* 配置信息管理器
*
* @author bwl
* @version 1.0
*/
public class ConfigManager {
/**
* 提供单例对象的静态内部类
*/
private static class SingletonHolder {
public static ConfigManager instance = new ConfigManager();
}
/**
* 获取对象实例
* @return
*/
public static ConfigManager getInstance() {
return SingletonHolder.instance;
}
/**
* 存储问题列表的Map
*/
private Map<String, Properties> name2properties;
/**
* 构造方法,请使用getInstance()获取实例
*/
private ConfigManager() {
name2properties = Collections.synchronizedMap(new HashMap<String, Properties>());
doInit();
}
/**
* 初始化方法
*/
private void doInit() {
try {
File path = new File("./conf/");
if (!path.exists()) {
System.out.println("ConfilgManager Init Error: There is no folder named 'conf' under src file.");
return;
}
File[] confFiles = path.listFiles(new DirFilter(".*//.properties"));////
for (int i = 0; i < confFiles.length; i++) {
File f = confFiles[i];
if (f.exists() && f.isFile()) {
Properties properties = new Properties();
InputStream is = new FileInputStream(f);
properties.load(is);
name2properties.put(f.getName(), properties);
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 获取配置项的值
* @param fileName 配置文件的名称
* @param key 关键码的值
* @return 配置项
*/
public String getProperty(String fileName, String key) {
if (fileName == null || fileName.length() == 0) {
return null;
}
Properties prop = name2properties.get(fileName);
if (prop != null) {
return prop.getProperty(key);
}
return null;
}
/**
* 获取整形的配置项的值
* @param fileName 配置文件的名称
* @param keyName 关键码的值
* @return 如果正确则返回数字,否则返回-1
*/
public int getIntProperty(String fileName, String key) {
String value = this.getProperty(fileName, key);
int result = -1;
if (value == null) {
return result;
}
try {
result = Integer.parseInt(value);
return result;
} catch (Exception e) {
//Do nothing
}
return result;
}
/**
* 过滤属性文件的内部类
*/
class DirFilter implements FilenameFilter {
/**
* 记录文件名格式的正则对象
*/
private Pattern pattern;
public DirFilter(String regex) {
pattern = Pattern.compile(regex);
}
public boolean accept(File dir, String name) {
return pattern.matcher(new File(name).getName()).matches();
}
}
public static void main(String[] args) {
ConfigManager config = ConfigManager.getInstance();
System.out.println(config.getIntProperty("cache.properties", "cache.size") + "");
System.out.println(config.getProperty("javagroups.properties", "bus_name") + "");
}
- java中Properties类的使用,网上文章整理
- java中Properties类的使用
- java中Properties类的使用
- java中Properties类的使用
- java中Properties类的使用
- java中Properties类的使用
- java中Properties类的使用
- java中Properties类的使用
- Java中Properties类的使用
- Java中Properties类的使用
- Java中Properties类的使用
- java中Properties类的使用2
- Java中Properties类的使用
- Java中Properties类的使用
- Java中Properties类的使用
- Java中Properties类的使用
- Java中Properties类的使用
- Java中Properties类的使用
- squid 緩存配置問題
- 为什么Oracle数据库不用索引来查找数据?
- Android中.jar包的应用
- 不管干什么,投入就好
- Java反射机制深入研究
- java中Properties类的使用,网上文章整理
- 什么是交叉编译
- java截断字符注意加转义
- qmail的白名单 - qmailtoaster whitlist
- Ubuntu 10.04 LTS 的窗口控制按钮从左上角调整到右上角
- JAVA反射性能测试
- BT协议的详细分析 ZZ
- 苹果iPad 2将于2011-3-11美国发售 中国无时间表
- Android开发:用eLocity平板机做真机调试出现的问题和解决方法