java读取properties属性文件值方法
2010-05-05 10:30
696 查看
在使用hibernate或者spring的时候,我们往往通过配置文件配置数据库连接属性。但这次项目中并没有用到hibernate和spring,只用到了struts2。要如何实现通过读取文件配置获取属性值呢?
方式一:ResourceBundle这个类可是实现读取properties文件来获取值
在java中:
在.properties文件中:
driverName=com.mysql.jdbc.Driver
url=xxxxx/:3307/9zgame?
user=root
password=xxxxxx
文件名字为:property_zh.properties。后zh根据Locale.CHINA一致的,如果Locale.ENGLISH,则文件名为:property_en.properties
方式二:使用commons组件。
需要使用jar包:commons-configuration-1.3.jar,commons-lang-2.3.jar,commons-collections.3.2.jar,commons-logging.jar
方式一:ResourceBundle这个类可是实现读取properties文件来获取值
在java中:
public class ResourceBundleReader { public final static Object initLock = new Object(); private final static String PROPERTIES_FILE_NAME = "property"; private static ResourceBundle bundle = null; static { try { if (bundle == null) { synchronized (initLock) { if (bundle == null) bundle = ResourceBundle.getBundle(PROPERTIES_FILE_NAME,Locale.CHINA); } } } catch (Exception e) { System.out.println("读取资源文件property_zh.properties失败!"); } } public static ResourceBundle getBundle() { return bundle; } public static void setBundle(ResourceBundle bundle) { bundle = bundle; } }
在.properties文件中:
driverName=com.mysql.jdbc.Driver
url=xxxxx/:3307/9zgame?
user=root
password=xxxxxx
文件名字为:property_zh.properties。后zh根据Locale.CHINA一致的,如果Locale.ENGLISH,则文件名为:property_en.properties
方式二:使用commons组件。
需要使用jar包:commons-configuration-1.3.jar,commons-lang-2.3.jar,commons-collections.3.2.jar,commons-logging.jar
public class ConfigReader { private static ConfigReader instance =new ConfigReader(); public static Configuration config ; private ConfigReader(){ try{ config = new PropertiesConfiguration("test.properties"); }catch(NestableRuntimeException e2){ System.out.println("properties read error..."); }catch(ConfigurationException e3){ System.out.println("properties read error..."); } } public static ConfigReader getInstance(){ return instance ; } public static void main(String args[]) throws RemoteException, NestableRuntimeException, ConfigurationException { System.out.println(ConfigReader.getInstance().config.getProperty("userid")); } }
相关文章推荐
- Java读取属性Properties文件的方法
- java读取properties属性文件值方法
- java读取Properties属性文件的方法
- Java中读取properties属性配置文件内容方法
- Java读取属性Properties文件的方法
- java代码及xml文件读取properties属性文件的方法
- java读取properties属性文件值方法
- java读取Properties属性文件的方法
- Java读取.properties资源文件的常用2种方法
- java读取properties文件方法和对比
- Java读取properties配置文件时,中文乱码解决方法
- 利用java.util.Properties读取属性文件
- java 读取 properties 文件方法 之一
- Java读取properties文件的简单方法
- Java读取Properties文件的六种方法
- java读取*.properties配置文件时,中文乱码解决方法
- java 读取properties文件的方法
- Java读取Properties文件的六种方法
- Java属性Properties文件读取工具类
- java读取.properties配置文件的几种方法