View Javadoc

1   /*
2    * Copyright (C) 2004 TiongHiang Lee
3    *
4    * This library is free software; you can redistribute it and/or
5    * modify it under the terms of the GNU Lesser General Public
6    * License as published by the Free Software Foundation; either
7    * version 2.1 of the License, or (at your option) any later version.
8    *
9    * This library is distributed in the hope that it will be useful,
10   * but WITHOUT ANY WARRANTY; without even the implied warranty of
11   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12   * Lesser General Public License for more details.
13   *
14   * You should have received a copy of the GNU Lesser General Public
15   * License along with this library; if not,  write to the Free Software
16   * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
17   *
18   * Email: thlee@onemindsoft.org
19   */
20  
21  package org.onemind.commons.java.util;
22  
23  import java.io.*;
24  import java.io.IOException;
25  import java.io.Writer;
26  import java.util.Iterator;
27  import java.util.Map;
28  /***
29   * A map utility class
30   * @author TiongHiang Lee (thlee@onemindsoft.org)
31   * @version $Id: MapUtils.java,v 1.3 2004/10/31 16:02:21 thlee Exp $ $Name:  $
32   */
33  public final class MapUtils
34  {
35  
36      /***
37       * {@inheritDoc}
38       */
39      private MapUtils()
40      {
41      };
42  
43      /***
44       * Dump the map in name=value lines
45       * @param m the map
46       * @param writer the writer
47       * @throws IOException if there's IO problem
48       */
49      public static void dump(Map m, Writer writer) throws IOException
50      {
51          Iterator it = m.keySet().iterator();
52          while (it.hasNext())
53          {
54              String key = (String) it.next();
55              writer.write(key + " = " + m.get(key) + "\n");
56          }
57      }
58  
59      /***
60       * Get a string representation of the content in the map
61       * @param m the map
62       * @return a string with the format of a=b separated by line break
63       * @throws IOException
64       */
65      public static String toString(Map m) throws IOException
66      {
67          ByteArrayOutputStream bout = new ByteArrayOutputStream();
68          Writer writer = new OutputStreamWriter(bout);
69          dump(m, writer);
70          writer.flush();
71          bout.close();
72          return new String(bout.toByteArray());        
73      }
74  }