配置文件读取工具类

package io.flysium.framework.util;


/**
 * 配置文件读取工具类
 */
public final class PropertiesUtils {

	private static Logger log = LoggerFactory.getLogger(PropertiesUtils.class);

	private static final String CLASSPATH_PREFIX = "classpath:";
	private static final String FILE_PREFIX = "file:";

	private PropertiesUtils() {
	}

	/**
	 * 
	 * @param vmName
	 *            启动应用是通过 -D设置的参数名称,如 CONFING_PATH、dubbo.protocol.port等
	 * @param classPathFileName
	 *            在classpath 下面的文件名,不带后缀,如 config.rocketmq
	 * @param fileName
	 *            文件全名,带后缀,如rocketmq.properties
	 * @return
	 */
	public static ResourceBundle getBundle(String vmName, String classPathFileName, String fileName) {
		ResourceBundle resource = null;
		String configPath = System.getProperty(vmName);// 获取vm动态参数
		if (configPath == null) {// 如果没有配置vm参数,根据classpath方式来获取
			resource = ResourceBundle.getBundle(classPathFileName, Locale.CHINA);
		} else {
			try {
				// 根据jvm参数配置的绝对路径获取
				if (configPath.startsWith(FILE_PREFIX)) {
					configPath = configPath.substring(FILE_PREFIX.length()) + File.separator + fileName;
				} else if (configPath.startsWith(CLASSPATH_PREFIX)) {
					configPath += "/" + fileName;
				}
				resource = getResourceBundle(configPath);
			} catch (Exception e) {
				log.error(e.getMessage(), e);
			}
		}
		return resource;
	}
	/**
	 * 注意使用完关闭inputstream流
	 * 
	 * @param vmName
	 *            启动应用是通过 -D设置的参数名称,如 CONFING_PATH、dubbo.protocol.port等
	 * @param fileName
	 *            文件全名,带后缀,如rocketmq.properties
	 * @return
	 */
	public static InputStream getBundleInputStream(String vmName, String fileName) {
		InputStream in = null;
		String configPath = System.getProperty(vmName);// 获取vm动态参数
		try {
			if (configPath == null) {// 如果没有配置vm参数,根据classpath方式来获取
				in = getResourceInputStream(fileName);
			} else {
				// 根据jvm参数配置的绝对路径获取
				if (configPath.startsWith(FILE_PREFIX)) {
					configPath = configPath.substring(FILE_PREFIX.length()) + File.separator + fileName;
				} else if (configPath.startsWith(CLASSPATH_PREFIX)) {
					configPath += "/" + fileName;
				}
				in = getResourceInputStream(configPath);
			}
		} catch (Exception e) {
			log.error(e.getMessage(), e);
		}
		return in;
	}

	/**
	 * 获取配置文件值(优先获取vm参数的值)
	 * 
	 * @param resource
	 * @param key
	 * @return
	 */
	public static String getString(ResourceBundle resource, String key) {
		String vmKey = System.getProperty(key);// 获取vm动态参数
		if (vmKey != null) {
			return vmKey;// 如果vm参数配置了该key,则优取该值
		}
		return resource.getString(key);
	}

	/**
	 * 支持读取在jar中的资源文件
	 * 
	 * @param resourceLocation
	 * @return
	 * @throws IOException
	 * @author SvenAugustus(蔡政滦) e-mail: SvenAugustus@outlook.com
	 * @version 2016年7月30日
	 */
	public static ResourceBundle getResourceBundle(String resourceLocation) throws IOException {
		Assert.notNull(resourceLocation, "Resource location must not be null");
		ResourceBundle resource = null;
		InputStream in = null;
		try {
			in = getResourceInputStream(resourceLocation);
			resource = new PropertyResourceBundle(in);
		} finally {
			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {
					log.error(e.getMessage(), e);
				}
			}
		}
		return resource;
	}

	/**
	 * 支持读取在jar中的资源文件
	 * 
	 * @param resourceLocation
	 * @return
	 * @throws IOException
	 * @author SvenAugustus(蔡政滦) e-mail: SvenAugustus@outlook.com
	 * @version 2016年7月30日
	 */
	public static InputStream getResourceInputStream(String resourceLocation) throws IOException {
		Assert.notNull(resourceLocation, "Resource location must not be null");
		InputStream in = null;
		if (resourceLocation.startsWith(CLASSPATH_PREFIX)) {
			String path = resourceLocation.substring(CLASSPATH_PREFIX.length());
			String description = (new StringBuilder()).append("class path resource [").append(path).append("]")
					.toString();
			ClassLoader cl = ClassUtils.getDefaultClassLoader();
			URL url = cl == null ? ClassLoader.getSystemResource(path) : cl.getResource(path);
			Assert.notNull(url, (new StringBuilder()).append(description)
					.append(" cannot be resolved to absolute file path because it does not exist").toString());

			if ("jar".equals(url.getProtocol())) {
				in = new ClassPathResource(path).getInputStream();
			} else if ("file".equals(url.getProtocol())) {
				File resourceFile = null;
				try {
					resourceFile = new File(ResourceUtils.toURI(url).getSchemeSpecificPart());
				} catch (URISyntaxException ex) {
					log.error(ex.getMessage(), ex);
					resourceFile = new File(url.getFile());
				}
				in = new FileInputStream(resourceFile);
			} else {
				throw new FileNotFoundException(
						(new StringBuilder()).append(description).append(" cannot be resolved to absolute file path ")
								.append("because it does not reside in the file system: ").append(url).toString());
			}
		}
		if (in == null) {
			File resourceFile = null;
			try {
				resourceFile = ResourceUtils.getFile(new URL(resourceLocation));
			} catch (MalformedURLException ex) {
				log.error(ex.getMessage(), ex);
				resourceFile = new File(resourceLocation);
			}
			in = new FileInputStream(resourceFile);
		}
		return in;
	}

}

以下是一个Java配置文件分段读取工具类,可以将配置文件按照section分段读取,每个section中的键值对以Map的形式存储: ```java import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.HashMap; import java.util.Map; public class ConfigParser { private String filename; private Map<String, Map<String, String>> sections; public ConfigParser(String filename) throws IOException { this.filename = filename; this.sections = new HashMap<>(); parse(); } public String get(String section, String option) { Map<String, String> options = sections.get(section); if (options != null) { return options.get(option); } return null; } public void set(String section, String option, String value) { Map<String, String> options = sections.computeIfAbsent(section, k -> new HashMap<>()); options.put(option, value); } private void parse() throws IOException { try (BufferedReader br = new BufferedReader(new FileReader(filename))) { String line; String section = null; Map<String, String> options = new HashMap<>(); while ((line = br.readLine()) != null) { line = line.trim(); if (line.matches("\\[.*\\]")) { if (section != null) { sections.put(section, options); } section = line.substring(1, line.length() - 1); options = new HashMap<>(); } else if (line.matches(".*=.*")) { String[] parts = line.split("=", 2); String option = parts[0].trim(); String value = parts[1].trim(); options.put(option, value); } } if (section != null) { sections.put(section, options); } } } } ``` 使用示例: ```java public static void main(String[] args) throws IOException { ConfigParser config = new ConfigParser("config.ini"); String value = config.get("section1", "option1"); System.out.println(value); config.set("section2", "option2", "value2"); // ... } ``` 其中,`config.ini`配置文件的格式如下: ``` [section1] option1 = value1 option2 = value2 [section2] option3 = value3 option4 = value4 ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值