您的位置:首页 > 编程语言 > Java开发

java读取配置文件Properties

2017-09-27 14:09 316 查看
Properties介绍博客:http://www.cnblogs.com/bakari/p/3562244.html

代码实例:

package com.self.cn.weather.env;

import org.apache.log4j.Logger;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class ServerEnvironment {

private static String apiUser = null;
private static String apiKey = null;
private static String apiGateway = null;
private static String sessionUrl = null;
private static Properties weatherMap = null;

static {
Properties properties = new Properties();
InputStream input = null;

ClassLoader classLoader = ServerEnvironment.class.getClassLoader();
try {
//根目录路径
System.out.println(ServerEnvironment.class.getResource("").getPath());
input = new FileInputStream(classLoader.getResource("configWeather.properties").getFile());
//input = new FileInputStream(classLoader.getResource("com/self/cn/weather/env/configWeather2.properties").getFile());
//获取class下指定文件夹中的配置文件
//方式一
//input = ServerEnvironment.class.getResourceAsStream("/properties/jdbc.properties");
//方式为
//input = new FileInputStream(classLoader.getResource("properties/jdbc.properties").getFile());
properties.load(input);
input.close();
} catch (IOException e) {
Logger.getLogger(ServerEnvironment.class).fatal("No Config file!", e);
}

ServerEnvironment.apiUser = properties.getProperty("api.user");
ServerEnvironment.apiKey = properties.getProperty("api.key");
ServerEnvironment.apiGateway = properties.getProperty("api.gateway");
ServerEnvironment.apiGateway = properties.getProperty("api.gateway");
ServerEnvironment.sessionUrl = properties.getProperty("id5.servlet.session");

InputStream mapInput = null;
try {
mapInput = new FileInputStream(classLoader.getResource("weather_map.properties").getFile());
weatherMap = new Properties();
weatherMap.load(mapInput);
mapInput.close();
} catch (IOException e) {
Logger.getLogger(ServerEnvironment.class).fatal("No Weather Map file!", e);
}
}

public static String getApiUser() {
return apiUser;
}

public static String getApiKey() {
return apiKey;
}

public static String getApiGateway() {
return apiGateway;
}

public static String getSessionUrl() {
return sessionUrl;
}

public static Properties getWeatherMap() {
return weatherMap;
}

public static void main(String[] args) {
System.out.println(ServerEnvironment.getApiUser());
}

}


文件路径:



二 方法类

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: