/* * Copyright (c) 2017. Panteng.Co.Ltd All rights reserved */ import org.apache.log4j.Logger; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.Properties; /** * @author panteng * @description * @date 17-2-7. */ public class PropertiesUtil { public static Logger logger = Logger.getLogger(PropertiesUtil.class); public static Properties pros = new Properties(); static { // 获取配置文件所在文件夹 String configDir = PropertiesUtil.class.getClassLoader().getResource("").getPath(); // 遍历文件夹下面的所有配置文件 File dir = new File(configDir); File[] files = dir.listFiles(); for (int i = 0; i < files.length; i++) { if (files[i].getName().indexOf(".properties") > -1) { InputStream path = PropertiesUtil.class.getClassLoader().getResourceAsStream(files[i].getName()); try { pros.load(path); } catch (IOException e) { logger.error("{}", e); } } } } }
对于打包成的jar包文件,需要读取jar里面的配置文件时,就会出现问题!对应修改如下:
/* * Copyright (c) 2017. Xiaomi.Co.Ltd All rights reserved */ package com.xiaomi.weather.utils; import org.apache.log4j.Logger; import java.io.*; import java.util.Properties; /** * @author panteng * @description * @date 17-2-7. */ public class PropertiesUtil { public static Logger logger = Logger.getLogger(PropertiesUtil.class); public static Properties pros = new Properties(); static { // 获取配置文件所在文件夹 String configDir = PropertiesUtil.class.getClassLoader().getResource("").getPath(); if (configDir.indexOf(".jar!") > -1) {//jar包 try { InputStream ips = PropertiesUtil.class.getResourceAsStream("/service.properties"); BufferedReader ipss = new BufferedReader(new InputStreamReader(ips)); pros.load(ipss); System.out.println("============================XXX" + pros.get("mongoHost")); } catch (Exception e) { e.printStackTrace(); } } else { // 遍历文件夹下面的所有配置文件 File dir = new File(configDir); File[] files = dir.listFiles(); for (int i = 0; i < files.length; i++) { if (files[i].getName().indexOf(".properties") > -1) { InputStream path = PropertiesUtil.class.getClassLoader().getResourceAsStream(files[i].getName()); try { pros.load(path); } catch (IOException e) { logger.error("{}", e); } } } } } }
获取jar内配置文件(scala):
val regularInputStream = this.getClass.getClassLoader.getResourceAsStream("regular.txt")
val regularBr = new BufferedReader(new InputStreamReader(regularInputStream))
var line: String = null
while ( {
line = regularBr.readLine();
line != null
}) {
val i1 = line.indexOf("\t")
val i2 = line.indexOf("\t", i1 + 1)
val i3 = line.indexOf("\t", i2 + 1)
val i4 = line.indexOf("\t", i3 + 1)
val i5 = line.indexOf("\t", i4 + 1)
descriptions.append(new Regex(line.substring(i4 + 1, i5)))
appIds.append(line.substring(i1 + 1, i2))
titles.append(null)
}