一般小工程,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;
-
-
-
-
-
-
-
- public class Tools {
- private static Properties p = new Properties();
-
-
-
-
- static{
- try {
- p.load(Tools.class.getClassLoader().getResourceAsStream("data.properties"));
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
-
-
-
- public static String getValue(String key)
- {
- return p.getProperty(key);
- }
- }
如此,调用配置文件中常量的时候,只要调用getValue()方法即可,比如
即 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;
-
-
-
-
-
-
-
- public class Tools {
-
- private static Properties p = new Properties();
- static {
- try {
-
-
- 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("读取配置信息出错!");
- }
- }
-
-
-
-
- public static String getValue(String key) {
- return p.getProperty(key);
- }
- }
打成jar包时,先移除config
利用Fat Jar打包,将生成的jar包与config文件夹放在同一路径即可。