背景:Web工程中,配置文件放的位置和读取方式,经常忘记。Web工程和可运行Jar工程不太一样。总结一下。
实现:
1. 首先,工程结构如下:
注:
a. 蓝色标注的两个文件是和com包平级的,都在src下。EnnNotificationPushProxy.ini是这个工程的配置文件,log4j.properties是log4j的配置文件。
b. 红色标注的两个文件,ConfigUtil.java是用来读取EnnNotificationPushProxy.ini的,LogUtil.java是读取log4j.properties的。
2. ConfigUtil.java内容:
package com.ecity.enn.notification.proxy.util; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Enumeration; import java.util.HashMap; import java.util.Properties; public class ConfigUtil { private static final String INI_FILE_NAME = "/EnnNotificationPushProxy.ini"; private static HashMap<String, String> propertyMap = null; static { propertyMap = new HashMap<String, String>(); String path = URLUtil.getClassPath(ConfigUtil.class) + INI_FILE_NAME; LogUtil.debug("EnnNotificationPushProxy.ini path=" + path); File file = new File(path); FileInputStream inStream = null; try { inStream = new FileInputStream(file); } catch (FileNotFoundException e) { LogUtil.error(e); } Properties properties = new Properties(); try { properties.load(inStream); } catch (IOException e) { LogUtil.error(e); } @SuppressWarnings("unchecked") Enumeration<String> keys = (Enumeration<String>) properties.propertyNames(); while (keys.hasMoreElements()) { String key = keys.nextElement(); propertyMap.put(key.toLowerCase(), properties.getProperty(key)); } } public static String get(String key) { return propertyMap.get(key.toLowerCase()); } public static int getInt(String key) { String valueStr = propertyMap.get(key.toLowerCase()); int value = 0; try { value = Integer.valueOf(valueStr); } catch (Exception e) { LogUtil.error(e); value = 0; } return value; } public static long getLong(String key) { String valueStr = propertyMap.get(key.toLowerCase()); long value = 0; try { value = Long.valueOf(valueStr); } catch (Exception e) { LogUtil.error(e); value = 0; } return value; } public static void set(String key, String value) { if (get(key) == null) { propertyMap.put(key, value); } } }
package com.ecity.enn.notification.proxy.util; import org.apache.log4j.Logger; import org.apache.log4j.PropertyConfigurator; public class LogUtil { private static final Logger logger; private static final String INI_FILE_NAME = "/log4j.properties"; private static final String TAG = "EnnNotificationPushProxy"; static { System.out.println("ProjectHomePath=" + URLUtil.getProjectHomePath()); System.setProperty("WORKDIR", URLUtil.getProjectHomePath()); String path = URLUtil.getClassPath(LogUtil.class) + INI_FILE_NAME; PropertyConfigurator.configure(path); logger = Logger.getLogger(TAG); } public static void debug(Object message) { logger.info(message); } public static void debug(String message, Throwable e) { logger.info(message, e); } public static void info(String message) { logger.info(message); } public static void info(String message, Throwable e) { logger.info(message, e); } public static void error(String message) { logger.error(message); } public static void error(Object message, Throwable e) { logger.error(message, e); } public static void error(Throwable e) { logger.error("", e); } }
注:注意WORKDIR的值的设置。它的值是当前工程的位置。
log4j.rootLogger=ALL, ServerDailyRollingFile, stdout log4j.appender.ServerDailyRollingFile=org.apache.log4j.DailyRollingFileAppender log4j.appender.ServerDailyRollingFile.DatePattern='.'yyyy-MM-dd log4j.appender.ServerDailyRollingFile.File=${WORKDIR}/logs/EnnNotificationPushProxy.log log4j.appender.ServerDailyRollingFile.layout=org.apache.log4j.PatternLayout log4j.appender.ServerDailyRollingFile.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %p [%c] %m%n log4j.appender.ServerDailyRollingFile.Append=true log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %p [%c] %m%n注:注意WORKDIR变量的使用。这个配置下,logs文件生成在工程的根目录。
5. 在ConfigUtil.java和LogUtil.java中,都使用到了URLUtil类。如下:
package com.ecity.enn.notification.proxy.util; import java.io.File; import java.io.UnsupportedEncodingException; import java.net.URL; /** * <p> * Title:URL辅助工具类 * </p> * * <p> * Copyright: 转载请注明出处http://blog.csdn.net/sunyujia/ * </p> * * @author 孙钰佳 * @main [email protected] * @date Sep 21, 2008 12:31:23 PM */ public class URLUtil { /** * * Description:取得当前类所在的文件 * * @param clazz * @return * @mail [email protected] * @since:Sep 21, 2008 12:32:10 PM */ public static File getClassFile(Class<?> clazz) { URL path = clazz.getResource(clazz.getName().substring(clazz.getName().lastIndexOf(".") + 1) + ".class"); if (path == null) { String name = clazz.getName().replaceAll("[.]", "/"); path = clazz.getResource("/" + name + ".class"); } return new File(path.getFile()); } /** * * Description:同getClassFile 解决中文编码问题 * * @param clazz * @return * @mail [email protected] * @since:Sep 21, 2008 1:10:12 PM */ public static String getClassFilePath(Class<?> clazz) { try { return java.net.URLDecoder.decode(getClassFile(clazz).getAbsolutePath(), "UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); return ""; } } /** * * Description:取得当前类所在的ClassPath目录 * * @param clazz * @return * @mail [email protected] * @since:Sep 21, 2008 12:32:27 PM */ public static File getClassPathFile(Class<?> clazz) { File file = getClassFile(clazz); for (int i = 0, count = clazz.getName().split("[.]").length; i < count; i++) file = file.getParentFile(); if (file.getName().toUpperCase().endsWith(".JAR!")) { file = file.getParentFile(); } return file; } /** * * Description: 同getClassPathFile 解决中文编码问题 * * @param clazz * @return * @mail [email protected] * @since:Sep 21, 2008 1:10:37 PM */ public static String getClassPath(Class<?> clazz) { try { return java.net.URLDecoder.decode(getClassPathFile(clazz).getAbsolutePath(), "UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); return ""; } } public static String getProjectHomePath() { String path = getClassPath(URLUtil.class); String webAppPath = path.substring(0, path.toUpperCase().lastIndexOf("WEB-INF")).replaceAll("%20", " "); return webAppPath; } public static void main(String[] args) throws UnsupportedEncodingException { System.out.println(getClassFilePath(URLUtil.class)); System.out.println(getClassPath(URLUtil.class)); } }注:这个类来自这个类来自 http://blog.csdn.net/sunyujia/。
6. 最终部署结果:
a. 两个配置文件的位置在classes下。如下:
b. logs文件夹在项目根目录下。log文件在logs文件夹下。如下: