11package com .ctrip .framework .apollo .core .utils ;
22
3+ import java .net .URL ;
34import org .slf4j .Logger ;
45import org .slf4j .LoggerFactory ;
56
@@ -43,8 +44,8 @@ public static Properties readConfigFile(String configPath, Properties defaults)
4344
4445 if (logger .isDebugEnabled ()) {
4546 StringBuilder sb = new StringBuilder ();
46- for (String sropertyName : props .stringPropertyNames ()) {
47- sb .append (sropertyName ).append ('=' ).append (props .getProperty (sropertyName )).append ('\n' );
47+ for (String propertyName : props .stringPropertyNames ()) {
48+ sb .append (propertyName ).append ('=' ).append (props .getProperty (propertyName )).append ('\n' );
4849
4950 }
5051 if (sb .length () > 0 ) {
@@ -58,6 +59,7 @@ public static Properties readConfigFile(String configPath, Properties defaults)
5859
5960 private static InputStream loadConfigFileFromDefaultSearchLocations (String configPath ) {
6061 try {
62+ // load from default search locations
6163 for (String searchLocation : DEFAULT_FILE_SEARCH_LOCATIONS ) {
6264 File candidate = Paths .get (searchLocation , configPath ).toFile ();
6365 if (candidate .exists () && candidate .isFile () && candidate .canRead ()) {
@@ -66,22 +68,35 @@ private static InputStream loadConfigFileFromDefaultSearchLocations(String confi
6668 }
6769 }
6870
69- InputStream in = ClassLoaderUtil .getLoader ().getResourceAsStream (configPath );
71+ // load from classpath
72+ URL url = ClassLoaderUtil .getLoader ().getResource (configPath );
7073
71- if (in != null ) {
72- logger .debug ("Reading config from resource {}" , ClassLoaderUtil .getLoader ().getResource (configPath ).getPath ());
73- return in ;
74- } else {
75- // load outside resource under current user path
76- File candidate = new File (System .getProperty ("user.dir" ) + configPath );
77- if (candidate .exists () && candidate .isFile () && candidate .canRead ()) {
78- logger .debug ("Reading config from resource {}" , candidate .getAbsolutePath ());
79- return new FileInputStream (candidate );
74+ if (url != null ) {
75+ InputStream in = getResourceAsStream (url );
76+
77+ if (in != null ) {
78+ logger .debug ("Reading config from resource {}" , url .getPath ());
79+ return in ;
8080 }
8181 }
82+
83+ // load outside resource under current user path
84+ File candidate = new File (System .getProperty ("user.dir" ), configPath );
85+ if (candidate .exists () && candidate .isFile () && candidate .canRead ()) {
86+ logger .debug ("Reading config from resource {}" , candidate .getAbsolutePath ());
87+ return new FileInputStream (candidate );
88+ }
8289 } catch (FileNotFoundException e ) {
8390 //ignore
8491 }
8592 return null ;
8693 }
87- }
94+
95+ private static InputStream getResourceAsStream (URL url ) {
96+ try {
97+ return url != null ? url .openStream () : null ;
98+ } catch (IOException e ) {
99+ return null ;
100+ }
101+ }
102+ }
0 commit comments