[关闭]
@tsing1226 2016-09-21T12:48:37.000000Z 字数 1868 阅读 1663

标签java

java读取properties文件的当前路径


  1. import java.io.BufferedReader;
  2. import java.io.FileInputStream;
  3. import java.io.InputStream;
  4. import java.io.InputStreamReader;
  5. import java.util.Properties;
  6. import org.slf4j.Logger;
  7. import org.slf4j.LoggerFactory;
  8. public class PropertiesUtil {
  9. static Logger logger = LoggerFactory.getLogger(PropertiesUtil.class);
  10. Properties memProperties = null;
  11. static String CONFIG_FILE = "zkManager.properties";
  12. public PropertiesUtil(String confFile) {
  13. CONFIG_FILE = confFile;
  14. }
  15. /**
  16. * 通过key获取配置值
  17. * @param key
  18. * @return
  19. * @throws Exception
  20. */
  21. public String getProperty(String key) throws Exception {
  22. return getProperty(key, null);
  23. }
  24. public String getProperty(String key, String defaultVl) throws Exception {
  25. if (null == memProperties) {
  26. logger.info("The memProperties is empty ,read properties from " + CONFIG_FILE);
  27. memProperties = loadPropertiesFromFile(null);
  28. }
  29. String value = memProperties.getProperty(key, defaultVl);
  30. if (null == value) {
  31. String info = "Cannot get valid value for the key:" + key + " from file " + CONFIG_FILE;
  32. throw new Exception(info);
  33. }
  34. return value;
  35. }
  36. /**
  37. * 读取配置文件
  38. * @param fileName:配置文件名称
  39. * @return
  40. */
  41. protected Properties loadPropertiesFromFile(String fileName) throws Exception {
  42. if (fileName == null || fileName.isEmpty()) {
  43. fileName = CONFIG_FILE;
  44. }
  45. //获取当前路径
  46. String localPath = this.getClass().getClassLoader().getResource(".").getPath();
  47. int idx = localPath.indexOf(":") + 1;
  48. localPath = localPath.substring(idx);
  49. logger.info("loadPropertiesFromFile, the target file path : " + localPath);
  50. memProperties = new Properties();
  51. FileInputStream in = null;
  52. try {
  53. String filePathName = localPath + fileName;
  54. in = new FileInputStream(filePathName);
  55. memProperties.load(in);
  56. } catch (Exception ex) {
  57. logger.error("Error occured when reading the properties file:" + localPath, ex);
  58. throw ex;
  59. } finally {
  60. if (in != null) {
  61. try {
  62. in.close();
  63. } catch (Exception ex) {
  64. //
  65. }
  66. in = null;
  67. }
  68. }
  69. return memProperties;
  70. }
  71. public static void main(String[] args) throws Exception {
  72. PropertiesUtil propUtil = new PropertiesUtil(CONFIG_FILE);
  73. //获得配置文件中的keyname所对应的值
  74. String str = propUtil.getProperty(keyname)
  75. }
  76. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注