Java项目和maven项目中如何获取&设置配置文件中的属性

通常情况下,我们会在一些配置文件文件中配置一些属性。如:

 

 

 

indexPath = E:\Tomcat_7.0\webapps\ipost_stage\lucene\index

imgUploadPath = E:\Tomcat_7.0\webapps\ipost_stage\attachedImg

imgPath=http://192.183.3.207/ipost_stage/attachedImg

adminEmail=

pageSize=5

normalImgSize=250

smallImgSize=100


通过打开编译后的classes目录(类路径目录)

 

 

那么可以通过工具类来实现对这个配置文件的读写。

首先建立一个常量类

/**

 * 常量类

 */

public class ConfigConstants {

//系统编码

public static final String CHARSET = "UTF-8";

//系统配置文件的路径

public static final String SYSCONFIG_PATH = "/sysConfig.properties";

}

然后通过一个工具类类操作

package com.myProject.common;

 

import java.io.File;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.InputStream;

import java.io.OutputStream;

import java.util.Date;

import java.util.Properties;

import com.myProject.utils.DateUtils;

 

/**

 * 读取公共的配置文件

 */

public class SysConfig {

private static Properties sysConfig = new Properties();

 

static { //读取配置文件

InputStream inputStream = SysConfig.class

.getResourceAsStream(ConfigConstants.SYSCONFIG_PATH);

try {

sysConfig.load(inputStream);

} catch (IOException e) {

e.printStackTrace();

} finally{

try {

inputStream.close();

} catch (IOException e) {

e.printStackTrace();

}

}

}

 

//根据属性读取配置文件

public static String getProperty(String key){

return sysConfig.getProperty(key);

}

 

//根据属性写入配置文件

public static void setProperty(String key,String value){

   sysConfig.setProperty(key, value);

}

 

}


测试类如下:

package com.myProject.test;

 

import com.myProject.common.SysConfig;

 

public class ConfigConstantTest {

public static void main(String[] args) {

String aa = SysConfig.getProperty("testConstant");

System.out.println(aa);

}

}

结果为:66

 

如果在maven项目中,常量类和工具类,测试类不变。唯一要变的就是系统配置文件的路径。那么怎么判断这里路径怎么写呢?

唯一的判断依据就是编译后的路径位置
在非maven项目中,直接看classes中的文件相对位置:

/sysConfig.properties就是直接定位到classes目录,然后在此目录中寻找sysConfig.properties文件。

maven项目中,则需要build之后看target目录中的classes目录,然后在此目录中寻找sysConfig.properties文件。

 

当然,方法有相对路径和绝对路径两种。

绝对路径:

则是这么配置:

/**

* 绝对路径配置:SYSCONFIG_PATH "/com/hori/bigData/resources/config.properties"

*/

相对路径是相对于常量类而言的,则是这么配置:

/**

* 相对路径配置:SYSCONFIG_PATH = "..\resources\config.properties"

*/

 

当然,考虑到windowslinux的兼容性,把  '/'换成‘\’即可

原文地址:https://www.cnblogs.com/osttwz/p/6899052.html