java读取properties文件

本文介绍了一种在Java中有效读取属性文件的方法,并对比了两种不同的实现方式:传统方式使用java.util.Properties类和使用Apache Commons Configuration库进行配置文件管理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


原:

读取的时候PropertiesUtils.getProperty("deviceName")

PROPERTIES_NAME 和类文件在一起的话可以只写文件名,否则要完整路径

开始写成这样不行,src/main/resources/config.properties



import java.io.FileInputStream;
import java.util.Properties;
public class PropertiesUtils {
private static final String PROPERTIES_NAME = "src\\main\\resources\\config.properties";
public static String getProperty(String key) {
String value = null;
FileInputStream in = null;
try {
Properties properties = new Properties();
in = new FileInputStream(PROPERTIES_NAME);
properties.load(in);
value = properties.getProperty(key);
//System.out.println("读取配置信息成功!");
} catch (Exception e) {
e.printStackTrace();
//System.out.println("读取配置信息失败!");
} finally {
if (in != null) {
try {
in.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
return value;
}


}

<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-configuration2</artifactId>
<version>2.0</version>
</dependency>

configuration2好用一些

import org.apache.commons.configuration2.PropertiesConfiguration;
import org.apache.commons.configuration2.builder.fluent.Configurations;
import org.apache.commons.configuration2.ex.ConfigurationException;

/**
 * @ClassName: Perconfig
 * @Description: TODO(这里用一句话描述这个类的作用)
 * @author jiangkai
 * @date 2017年11月13日 下午2:17:58
 */
//@SuppressWarnings("restriction")
//@SuppressWarnings("restriction")
@Service("perconfig")
//@Repository(value="perconfig")
//@Component
public class Perconfig {
private Logger log = LoggerFactory.getLogger(Perconfig.class);
PropertiesConfiguration pluginConfig = null;


@SuppressWarnings("restriction")
@PostConstruct
public void loadConfig() {
log.info("load configurations start...");
Configurations conf = new Configurations();
try {
pluginConfig = conf.properties("plugin.properties");
} catch (ConfigurationException e) {
// e.printStackTrace();
log.error("load plugin.properties error", e);
}
}


@Override
public String toString() {
// TODO Auto-generated method stub
return "kkk";
}


public PropertiesConfiguration getConfiguration() {
return pluginConfig;
}


}




使用时Perconfig 

String ss = perconfig.getConfiguration().getString("plugin.id");

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值