java读取properties文件

来源:互联网 发布:冬未了 知乎 编辑:程序博客网 时间:2024/06/05 15:01


原:

读取的时候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;
}


}

原创粉丝点击