转载:https://blog.csdn.net/sdsky1987/article/details/7418101
一般小工程,properties配置文件之间在src根目录创建
比如data.properties,代码如下
- <!-- 代理服务器地址 -->
- PROXY=192.168.0.1
- <!-- 代理服务器端口号 -->
- PORT=8080
- <!-- 登录代理的用户名 -->
- USERNAME=username
- <!-- 登录代理的口令 -->
- PASSWORD=password
- <!-- 图片存储路径 -->
- imgPath=c:/xml/
- <!-- xml文件名 -->
- xmlName=UploadRequest.xml
- <!-- 1. Build Fat Jar包含dom4j -->
- <!-- 2. cmd - 生成的jar路径下 java -jar xx.jar -->
- <!-- properties配置文件更新困难 -->
用于读取数据的工具类如下写:
- package com.main.util;
- import java.io.IOException;
- import java.util.Properties;
- /**
- *
- * 读取properties文件的工具类
- *
- * @author 莫小哆_ly 2012-3-30
- */
- public class Tools {
- private static Properties p = new Properties();
- /**
- * 读取properties配置文件信息
- */
- static{
- try {
- p.load(Tools.class.getClassLoader().getResourceAsStream("data.properties"));
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- /**
- * 根据key得到value的值
- */
- public static String getValue(String key)
- {
- return p.getProperty(key);
- }
- }
如此,调用配置文件中常量的时候,只要调用getValue()方法即可,比如
- Tools.getValue("PORT")
即 8080
========================================================================
另外,项目中也经常单独将一部分功能独立做Java Project,然后打成jar包供其他项目调用。如果jar包中需要读取配置文件信息,则很少把该配置打进jar包,因为它不方便修改,更多都是采用jar包读取外部配置文件。
properties配置文件从工程移除,先放在工程下、与src并列路径。如图
读取配置文件的工具类Tools做如下改动:
- package com.main.util;
- import java.io.BufferedInputStream;
- import java.io.FileInputStream;
- import java.io.IOException;
- import java.io.InputStream;
- import java.util.Properties;
- /**
- *
- * 读取properties文件的工具类
- *
- * @author 莫小哆_ly 2012-3-30
- */
- public class Tools {
- private static Properties p = new Properties();
- static {
- try {
- // System.getProperty("user.dir") 获得项目的绝对路径,然后拼装配置文件的路径
- // 读取系统外配置文件 (即Jar包外文件) --- 外部工程引用该Jar包时需要在工程下创建config目录存放配置文件
- String filePath = System.getProperty("user.dir") + "/config/data.properties";
- InputStream in = new BufferedInputStream(new FileInputStream(filePath));
- p.load(in);
- } catch (IOException e) {
- System.out.println("读取配置信息出错!");
- }
- }
- /**
- * 根据key得到value的值
- */
- public static String getValue(String key) {
- return p.getProperty(key);
- }
- }