enoeht的Java源码系列(4)--继续处理配置文件

来源:互联网 发布:哪些智障广告知乎 编辑:程序博客网 时间:2024/05/13 05:27

我们还常常会在程序中用到这样的配置文件:

[section]

key = value

下面是一个这种配置文件中的实例

[Server]

    Address=192.168.1.151

    Port=8000

    Version=1

    Info=1

[User]

    Name=Kyle

    Pwd=1234

[ID]

    111;222;333

[END]

 

在这里提供了一个处理这种结构的配置文件的类的源代码:

package org.kyle.util;

 

import java.util.*;

import java.io.*;

 

public class CfgArea

{

    char m_start, m_end;

    String m_commentTag = "#"; //配置文件中#开头的是注释

    String m_valueDelim = null;

    String m_areaName = null;

    HashMap m_content = new HashMap();

    String m_nextName = null;

 

    public CfgArea(char areaTagStart, char areaTagEnd)

    {

        this( areaTagStart, areaTagEnd, null );

    }

 

    public void reset()

    {

        m_areaName = m_nextName;

        m_nextName = null;

        m_content.clear();

    }

 

    public CfgArea(char areaTagStart, char areaTagEnd, String cTag)

    {

        m_start = areaTagStart;

        m_end = areaTagEnd;

        if ( cTag != null ) m_commentTag = cTag;

    }

 

    public void setValueDelim( String vDlm )

    {

        m_valueDelim = vDlm;

    }

 

    public String getName()

    {

        return m_areaName;

    }

 

    public String getValue( String sKey )

    {

        return (String)m_content.get( sKey );

    }

 

    public Set getKeys()

    {

        return m_content.keySet();

    }

 

    public boolean readArea( BufferedReader br)

    {

        try

        {

            String aLine = null;

            while( (aLine = readCfgLine( br ) )  != null )

            {

                if ( aLine.trim().equals("") ) continue;

 

                if ( m_areaName == null )

                {

                    m_areaName = getAreaName( aLine );

                    if ( m_areaName == null ) return false;

                    continue;

                }

                else

                {

                    if ( restoreTag( aLine ) ) return true;

                }

 

                if ( m_valueDelim != null )

                {

                    addKeys( aLine, m_valueDelim );

                }

                else

                    addKeyPair( aLine );

            }

 

           //System.out.println( m_content );

 

            return aLine != null;

        }

        catch( Exception e)

        {

            Debug.warning("readArea exception in Class CfgArea");

        }

 

        return false;

    }

 

    private String readCfgLine( BufferedReader theReader )

        throws IOException

    {

        String aLine = null;

        do{

            aLine = theReader.readLine();

        }while( aLine !=null && (aLine.trim().equals("") || aLine.trim().startsWith( m_commentTag ) ) );

 

        return aLine == null ? null : aLine.trim();

    }

 

    private boolean isAreaTag( String aLine )

    {

        char[] lineChars = aLine.toCharArray();

        return lineChars[0] == m_start && lineChars[ lineChars.length - 1 ] == m_end ;

    }

 

    private String getAreaName( String aLine )

    {

        if ( !isAreaTag( aLine ) ) return null;

        StringBuffer sb = new StringBuffer( aLine );

        sb.deleteCharAt( 0 );

        sb.deleteCharAt( sb.length() - 1 );

        return sb.toString();

    }

 

    private void addKeyPair( String aLine )

    {

        StringTokenizer st = new StringTokenizer( aLine, "=" );

        String sKey = null, sVal = null;

        if( st.hasMoreTokens()  )

            sKey = st.nextToken();

        if( st.hasMoreTokens()  )

            sVal = st.nextToken();

        if ( sKey == null ) return;

        m_content.put( sKey, sVal );

    }

 

    private void addKeys( String aLine, String delim )

    {

        StringTokenizer st = new StringTokenizer( aLine, delim );

        String sKey = null;

        while( st.hasMoreTokens()  )

        {

            sKey = st.nextToken();

            m_content.put( sKey, m_areaName );

       }

 

    }

 

    private boolean restoreTag( String areaTag)

        throws IOException

    {

        if ( !isAreaTag( areaTag )  ) return false;

        m_nextName = getAreaName( areaTag );

        return true;

    }

}

 

 

下面我们来看这个类怎么用:

  private static Hashtable properties = new Hashtable();

  try {

      BufferedReader pbr = new BufferedReader(new InputStreamReader(new

          FileInputStream("Property.cfg")));

      CfgArea ca = new CfgArea('[', ']'); //除了用[]来标识section,还可以用其他字符呦。

      ca.readArea(pbr);

      Hashtable H1 = new Hashtable();

      H1.put("ServerName", ca.getName());

      H1.put("Address", ca.getValue("Address"));

      H1.put("Port", ca.getValue("Port"));

      properties.put(ca.getName(), H1);

      ca.reset();

      //开始读下一个section

      ca.readArea(pbr);

      Hashtable H2 = new Hashtable();

      H2.put("User", ca.getName());

      H2.put("Name", ca.getValue("Name"));

      H2.put("Pwd", ca.getValue("Pwd"));

      properties.put(ca.getName(), H2);

      ca.reset();

      //第三个section与前两个有些不同,可以把他看成只有key

      ca.setValueDelim(";"); //key中是由;号分隔的

      ca.readArea(pbr);

      Hashtable H3 = new Hashtable();

      Iterator iKey = ca.getKeys().iterator();

      while (iKey.hasNext()) {

          H3.put( (String) iKey.next(), ca.getName());

      }

      properties.put(ca.getName(), H3);

      ca.reset();

      pbr.close();

    }

    catch (Exception e) {

      properties.clear();

      e.printStackTrace();

    }

 

原创粉丝点击