1+ package com .devil .utils ;
2+
3+ import java .io .IOException ;
4+ import java .io .InputStream ;
5+ import java .io .Reader ;
6+ import java .io .StringReader ;
7+ import java .util .Properties ;
8+ import java .util .regex .Matcher ;
9+ import java .util .regex .Pattern ;
10+ import java .util .Map .Entry ;
11+
12+ /**
13+ * root=/a
14+ * file=${root}/c
15+ * @author xqs
16+ */
17+ public class VarProperties extends Properties {
18+ private static final long serialVersionUID = 1L ;
19+ private static final Pattern PATTERN = Pattern .compile ("\\ $\\ {([^\\ }]+)\\ }" );
20+
21+ public static void main (String [] args ){
22+ Properties prop =new VarProperties ();
23+ Reader reader = new StringReader ("root=aaa\n file=${root}/test" );
24+ try {
25+ prop .load (reader );
26+ } catch (IOException e ) {
27+ e .printStackTrace ();
28+ }
29+ System .out .println (prop .getProperty ("file" ));
30+ }
31+
32+ @ Override
33+ public synchronized void load (InputStream inStream ) throws IOException {
34+ super .load (inStream );
35+ for (Entry <Object , Object > entry : this .entrySet ()) {
36+ entry .setValue (getRealProperty ((String ) entry .getKey (), (String ) entry .getValue ()));
37+ }
38+ }
39+
40+ @ Override
41+ public synchronized void load (Reader reader ) throws IOException {
42+ super .load (reader );
43+ for (Entry <Object , Object > entry : this .entrySet ()) {
44+ entry .setValue (getRealProperty ((String ) entry .getKey (), (String ) entry .getValue ()));
45+ }
46+ }
47+
48+ private String getRealProperty (String key ,String value ){
49+ Matcher matcher = PATTERN .matcher (value );
50+ StringBuffer buffer = new StringBuffer ();
51+ while (matcher .find ()) {
52+ String matcherKey = matcher .group (1 );
53+ String matchervalue = this .getProperty (matcherKey );
54+ if (matchervalue != null ) {
55+ matcher .appendReplacement (buffer , matchervalue );
56+ }
57+ }
58+ matcher .appendTail (buffer );
59+ return buffer .toString ();
60+ }
61+ }
0 commit comments