设为首页 收藏本站
查看: 543|回复: 0

[经验分享] 读取项目src下等的配置文件,适合于weblogic,tomcat等多种不同的容器。

[复制链接]

尚未签到

发表于 2015-8-7 10:24:02 | 显示全部楼层 |阅读模式
DSC0000.jpg
  JAVA类:
  1、ServiceCfgLoader。



package org.sinosoft.perfect.common;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import org.sinosoft.perfect.exception.FileException;
/**
*
* @author fengys
*
*/
public class ServiceCfgLoader {
public static void main(String[] args) {
ServiceCfgLoader serviceCfgLoader = new ServiceCfgLoader("");
}
private Map propertiesMap;
public ServiceCfgLoader(String name) {
URL settingsUrl = ClassLoaderUtil.getResource(name + ".properties", getClass());
if (settingsUrl == null) {
//            if (LOG.isDebugEnabled()) {
//                LOG.debug(name + ".properties missing");
//            }
settingsUrl = ClassLoaderUtil.getResource("org/sinosoft/perfect/common/ws.smp.default" + ".properties", getClass());
}
System.out.println("文件位置" + settingsUrl.toString());
InputStream in = null;
try {
in = settingsUrl.openStream();
Reader reader = new InputStreamReader(in);
PropertiesReader pr = new PropertiesReader(reader);
propertiesMap = new HashMap();
while (pr.nextProperty()) {
String name2 = pr.getPropertyName();
String val = pr.getPropertyValue();
//int line = pr.getLineNumber();
                propertiesMap.put(name2, val);
}
} catch (IOException e) {
throw new FileException("Could not load " + name + ".properties:"
+ e, e);
} finally {
if (in != null) {
try {
in.close();
} catch (IOException io) {
io.printStackTrace();
}
}
}
}
public Map getPropertiesMap(){
if(propertiesMap == null){
propertiesMap = new HashMap();
}
return propertiesMap;
}
}
  
辅助类:
  1、ClassLoaderUtil类和PropertiesReader类:



package org.sinosoft.perfect.common;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.*;
public class ClassLoaderUtil {
public static Iterator getResources(String resourceName, Class callingClass, boolean aggregate) throws IOException {
AggregateIterator iterator = new AggregateIterator();
iterator.addEnumeration(Thread.currentThread().getContextClassLoader().getResources(resourceName));
if (!iterator.hasNext() || aggregate) {
iterator.addEnumeration(ClassLoaderUtil.class.getClassLoader().getResources(resourceName));
}
if (!iterator.hasNext() || aggregate) {
ClassLoader cl = callingClass.getClassLoader();
if (cl != null) {
iterator.addEnumeration(cl.getResources(resourceName));
}
}
if (!iterator.hasNext() && (resourceName != null) && ((resourceName.length() == 0) || (resourceName.charAt(0) != '/'))) {
return getResources('/' + resourceName, callingClass, aggregate);
}
return iterator;
}
public static URL getResource(String resourceName, Class callingClass) {
URL url = Thread.currentThread().getContextClassLoader().getResource(resourceName);
if (url == null) {
url = ClassLoaderUtil.class.getClassLoader().getResource(resourceName);
}
if (url == null) {
ClassLoader cl = callingClass.getClassLoader();
if (cl != null) {
url = cl.getResource(resourceName);
}
}
if ((url == null) && (resourceName != null) && ((resourceName.length() == 0) || (resourceName.charAt(0) != '/'))) {
return getResource('/' + resourceName, callingClass);
}
return url;
}
public static InputStream getResourceAsStream(String resourceName, Class callingClass) {
URL url = getResource(resourceName, callingClass);
try {
return (url != null) ? url.openStream() : null;
} catch (IOException e) {
return null;
}
}
public static Class loadClass(String className, Class callingClass) throws ClassNotFoundException {
try {
return Thread.currentThread().getContextClassLoader().loadClass(className);
} catch (ClassNotFoundException e) {
try {
return Class.forName(className);
} catch (ClassNotFoundException ex) {
try {
return ClassLoaderUtil.class.getClassLoader().loadClass(className);
} catch (ClassNotFoundException exc) {
return callingClass.getClassLoader().loadClass(className);
}
}
}
}
static class AggregateIterator implements Iterator {
LinkedList enums = new LinkedList();
Enumeration cur = null;
E next = null;
Set loaded = new HashSet();
public AggregateIterator addEnumeration(Enumeration e) {
if (e.hasMoreElements()) {
if (cur == null) {
cur = e;
next = e.nextElement();
loaded.add(next);
} else {
enums.add(e);
}
}
return this;
}
public boolean hasNext() {
return (next != null);
}
public E next() {
if (next != null) {
E prev = next;
next = loadNext();
return prev;
} else {
throw new NoSuchElementException();
}
}
private Enumeration determineCurrentEnumeration() {
if (cur != null && !cur.hasMoreElements()) {
if (enums.size() > 0) {
cur = enums.removeLast();
} else {
cur = null;
}
}
return cur;
}
private E loadNext() {
if (determineCurrentEnumeration() != null) {
E tmp = cur.nextElement();
int loadedSize = loaded.size();
while (loaded.contains(tmp)) {
tmp = loadNext();
if (tmp == null || loaded.size() > loadedSize) {
break;
}
}
if (tmp != null) {
loaded.add(tmp);
}
return tmp;
}
return null;
}
public void remove() {
throw new UnsupportedOperationException();
}
}
}


package org.sinosoft.perfect.common;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
public class PropertiesReader extends LineNumberReader
{
/** Stores the comment lines for the currently processed property.*/
private List commentLines;
/** Stores the name of the last read property.*/
private String propertyName;
/** Stores the value of the last read property.*/
private String propertyValue;
/** Stores the list delimiter character.*/
private char delimiter;
/** Constant for the supported comment characters.*/
static final String COMMENT_CHARS = "#!";
/** Constant for the radix of hex numbers.*/
private static final int HEX_RADIX = 16;
/** Constant for the length of a unicode literal.*/
private static final int UNICODE_LEN = 4;
/** The list of possible key/value separators */
private static final char[] SEPARATORS = new char[] {'=', ':'};
/** The white space characters used as key/value separators. */
private static final char[] WHITE_SPACE = new char[]{' ', '\t', '\f'};
/**
* Constructor.
*
* @param reader A Reader.
*/
public PropertiesReader(Reader reader)
{
this(reader, ',');
}
/**
* Creates a new instance of PropertiesReader and sets
* the underlaying reader and the list delimiter.
*
* @param reader the reader
* @param listDelimiter the list delimiter character
* @since 1.3
*/
public PropertiesReader(Reader reader, char listDelimiter)
{
super(reader);
commentLines = new ArrayList();
delimiter = listDelimiter;
}
/**
* Tests whether a line is a comment, i.e. whether it starts with a comment
* character.
*
* @param line the line
* @return a flag if this is a comment line
* @since 1.3
*/
boolean isCommentLine(String line)
{
String s = line.trim();
// blanc lines are also treated as comment lines
return s.length() < 1 || COMMENT_CHARS.indexOf(s.charAt(0)) >= 0;
}
/**
* Reads a property line. Returns null if Stream is
* at EOF. Concatenates lines ending with "\".
* Skips lines beginning with "#" or "!" and empty lines.
* The return value is a property definition (&lt;name&gt;
* = &lt;value&gt;)
*
* @return A string containing a property value or null
*
* @throws IOException in case of an I/O error
*/
public String readProperty() throws IOException
{
commentLines.clear();
StringBuilder buffer = new StringBuilder();
while (true)
{
String line = readLine();
if (line == null)
{
// EOF
return null;
}
if (isCommentLine(line))
{
commentLines.add(line);
continue;
}
line = line.trim();
if (checkCombineLines(line))
{
line = line.substring(0, line.length() - 1);
buffer.append(line);
}
else
{
buffer.append(line);
break;
}
}
return buffer.toString();
}
/**
* Parses the next property from the input stream and stores the found
* name and value in internal fields. These fields can be obtained using
* the provided getter methods. The return value indicates whether EOF
* was reached (false) or whether further properties are
* available (true).
*
* @return a flag if further properties are available
* @throws IOException if an error occurs
* @since 1.3
*/
public boolean nextProperty() throws IOException
{
String line = readProperty();
if (line == null)
{
return false; // EOF
        }
// parse the line
String[] property = parseProperty(line);
propertyName = unescapeJava(property[0]);
propertyValue = unescapeJava(property[1], delimiter);
return true;
}
/**
* Returns the comment lines that have been read for the last property.
*
* @return the comment lines for the last property returned by
* readProperty()
* @since 1.3
*/
public List getCommentLines()
{
return commentLines;
}
/**
* Returns the name of the last read property. This method can be called
* after {@link #nextProperty()} was invoked and its
* return value was true.
*
* @return the name of the last read property
* @since 1.3
*/
public String getPropertyName()
{
return propertyName;
}
/**
* Returns the value of the last read property. This method can be
* called after {@link #nextProperty()} was invoked and
* its return value was true.
*
* @return the value of the last read property
* @since 1.3
*/
public String getPropertyValue()
{
return propertyValue;
}
/**
* Checks if the passed in line should be combined with the following.
* This is true, if the line ends with an odd number of backslashes.
*
* @param line the line
* @return a flag if the lines should be combined
*/
private boolean checkCombineLines(String line)
{
int bsCount = 0;
for (int idx = line.length() - 1; idx >= 0 && line.charAt(idx) == '\\'; idx--)
{
bsCount++;
}
return bsCount % 2 == 1;
}
/**
* Parse a property line and return the key and the value in an array.
*
* @param line the line to parse
* @return an array with the property's key and value
* @since 1.2
*/
private String[] parseProperty(String line)
{
// sorry for this spaghetti code, please replace it as soon as
// possible with a regexp when the Java 1.3 requirement is dropped

String[] result = new String[2];
StringBuilder key = new StringBuilder();
StringBuilder value = new StringBuilder();
// state of the automaton:
// 0: key parsing
// 1: antislash found while parsing the key
// 2: separator crossing
// 3: value parsing
int state = 0;
for (int pos = 0; pos < line.length(); pos++)
{
char c = line.charAt(pos);
switch (state)
{
case 0:
if (c == '\\')
{
state = 1;
}
else if (contains(WHITE_SPACE, c))
{
// switch to the separator crossing state
state = 2;
}
else if (contains(SEPARATORS, c))
{
// switch to the value parsing state
state = 3;
}
else
{
key.append(c);
}
break;
case 1:
if (contains(SEPARATORS, c) || contains(WHITE_SPACE, c))
{
// this is an escaped separator or white space
                        key.append(c);
}
else
{
// another escaped character, the '\' is preserved
key.append('\\');
key.append(c);
}
// return to the key parsing state
state = 0;
break;
case 2:
if (contains(WHITE_SPACE, c))
{
// do nothing, eat all white spaces
state = 2;
}
else if (contains(SEPARATORS, c))
{
// switch to the value parsing state
state = 3;
}
else
{
// any other character indicates we encoutered the beginning of the value
                        value.append(c);
// switch to the value parsing state
state = 3;
}
break;
case 3:
value.append(c);
break;
}
}
result[0] = key.toString().trim();
result[1] = value.toString().trim();
return result;
}
/**
* Unescapes any Java literals found in the String to a
* Writer. This is a slightly modified version of the
* StringEscapeUtils.unescapeJava() function in commons-lang that doesn't
* drop escaped separators (i.e '\,').
*
* @param str  the String to unescape, may be null
* @param delimiter the delimiter for multi-valued properties
* @return the processed string
* @throws IllegalArgumentException if the Writer is null
*/
protected static String unescapeJava(String str, char delimiter)
{
if (str == null)
{
return null;
}
int sz = str.length();
StringBuilder out = new StringBuilder(sz);
StringBuffer unicode = new StringBuffer(UNICODE_LEN);
boolean hadSlash = false;
boolean inUnicode = false;
for (int i = 0; i < sz; i++)
{
char ch = str.charAt(i);
if (inUnicode)
{
// if in unicode, then we're reading unicode
// values in somehow
                unicode.append(ch);
if (unicode.length() == UNICODE_LEN)
{
// unicode now contains the four hex digits
// which represents our unicode character
try
{
int value = Integer.parseInt(unicode.toString(), HEX_RADIX);
out.append((char) value);
unicode.setLength(0);
inUnicode = false;
hadSlash = false;
}
catch (NumberFormatException nfe)
{
throw new RuntimeException("Unable to parse unicode value: " + unicode, nfe);
}
}
continue;
}
if (hadSlash)
{
// handle an escaped value
hadSlash = false;
if (ch == '\\')
{
out.append('\\');
}
else if (ch == '\'')
{
out.append('\'');
}
else if (ch == '\"')
{
out.append('"');
}
else if (ch == 'r')
{
out.append('\r');
}
else if (ch == 'f')
{
out.append('\f');
}
else if (ch == 't')
{
out.append('\t');
}
else if (ch == 'n')
{
out.append('\n');
}
else if (ch == 'b')
{
out.append('\b');
}
else if (ch == delimiter)
{
out.append('\\');
out.append(delimiter);
}
else if (ch == 'u')
{
// uh-oh, we're in unicode country....
inUnicode = true;
}
else
{
out.append(ch);
}
continue;
}
else if (ch == '\\')
{
hadSlash = true;
continue;
}
out.append(ch);
}
if (hadSlash)
{
// then we're in the weird case of a \ at the end of the
// string, let's output it anyway.
out.append('\\');
}
return out.toString();
}
/**
* Checks if the object is in the given array.
*
* The method returns false if a null array is passed in.
*
* @param array  the array to search through
* @param objectToFind  the object to find
* @return true if the array contains the object
*/
public boolean contains(char[] array, char objectToFind) {
if (array == null) {
return false;
}
for (char anArray : array) {
if (objectToFind == anArray) {
return true;
}
}
return false;
}
/**
* Unescapes any Java literals found in the String.
* For example, it will turn a sequence of '\' and
* 'n' into a newline character, unless the '\'
* is preceded by another '\'.
*
* @param str  the String to unescape, may be null
* @return a new unescaped String, null if null string input
*/
public static String unescapeJava(String str) {
if (str == null) {
return null;
}
try {
StringWriter writer = new StringWriter(str.length());
unescapeJava(writer, str);
return writer.toString();
} catch (IOException ioe) {
// this should never ever happen while writing to a StringWriter
            ioe.printStackTrace();
return null;
}
}
/**
* Unescapes any Java literals found in the String to a
* Writer.
*
* For example, it will turn a sequence of '\' and
* 'n' into a newline character, unless the '\'
* is preceded by another '\'.
*
* A null string input has no effect.
*
* @param out  the Writer used to output unescaped characters
* @param str  the String to unescape, may be null
* @throws IllegalArgumentException if the Writer is null
* @throws IOException if error occurs on underlying Writer
*/
public static void unescapeJava(Writer out, String str) throws IOException {
if (out == null) {
throw new IllegalArgumentException("The Writer must not be null");
}
if (str == null) {
return;
}
int sz = str.length();
StringBuffer unicode = new StringBuffer(4);
boolean hadSlash = false;
boolean inUnicode = false;
for (int i = 0; i < sz; i++) {
char ch = str.charAt(i);
if (inUnicode) {
// if in unicode, then we're reading unicode
// values in somehow
                unicode.append(ch);
if (unicode.length() == 4) {
// unicode now contains the four hex digits
// which represents our unicode character
try {
int value = Integer.parseInt(unicode.toString(), 16);
out.write((char) value);
unicode.setLength(0);
inUnicode = false;
hadSlash = false;
} catch (NumberFormatException nfe) {
throw new RuntimeException("Unable to parse unicode value: " + unicode, nfe);
}
}
continue;
}
if (hadSlash) {
// handle an escaped value
hadSlash = false;
switch (ch) {
case '\\':
out.write('\\');
break;
case '\'':
out.write('\'');
break;
case '\"':
out.write('"');
break;
case 'r':
out.write('\r');
break;
case 'f':
out.write('\f');
break;
case 't':
out.write('\t');
break;
case 'n':
out.write('\n');
break;
case 'b':
out.write('\b');
break;
case 'u':
{
// uh-oh, we're in unicode country....
inUnicode = true;
break;
}
default :
out.write(ch);
break;
}
continue;
} else if (ch == '\\') {
hadSlash = true;
continue;
}
out.write(ch);
}
if (hadSlash) {
// then we're in the weird case of a \ at the end of the
// string, let's output it anyway.
out.write('\\');
}
}
}
  3、配置文件ws.smp.default.properties
ip=localhost
port=8080
  4、异常类FileException



package org.sinosoft.perfect.exception;
public class FileException extends RuntimeException{
private static final long serialVersionUID = 888724366243600135L;
public FileException() {
}
public FileException(String s) {
this(s, null, null);
}
public FileException(String s, Object target) {
this(s, (Throwable) null, target);
}
public FileException(Throwable cause) {
this(null, cause, null);
}
public FileException(Throwable cause, Object target) {
this(null, cause, target);
}
public FileException(String s, Throwable cause) {
super(s, cause);
}
public FileException(String s, Throwable cause, Object target) {
super(s, cause);
}
}
  最后,包结构如下:
  
  
  

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-95097-1-1.html 上篇帖子: Tomcat,Weblogic,WebSphere,JBoss四种服务器简单对比 下篇帖子: Tomcat/weblogic session失效时间的几种设置方法
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表