工作中写的一些东西:
/**
 * 操作配置文件
 * @author chou
 * @version [版本号,2008-07-20]
 * @see [相关类/方法]
 * @since [产品/模块版本]
 */
public class ResourceConfig
{
    /**
     * 获得指定文件的流对象
     * @param fileName  文件名
     * @return  指向文件的流
     */
    public static InputStream getConfigFileStream(String fileName)
    {
        return ResourceConfig.class.getResourceAsStream(fileName);
    }
   
    /**
     * 获取配置文件内容
     * @param fileName 文件名
     * @return  文件内容
     */
    public static String getConfigFileContent(String fileName)
    {
        InputStream inputStream = ResourceConfig.class.getResourceAsStream(fileName);
        BufferedInputStream in = new BufferedInputStream(inputStream);
        ByteArrayOutputStream out = new ByteArrayOutputStream(10240);
        byte[] buf = new byte[1024];
        int len;
        try
        {
            while ((len = in.read(buf)) >= 0)
            {
                out.write(buf, 0, len);
            }
            in.close();
        }
        catch (IOException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } 
    
        return new String(out.toByteArray());
    }
   
    /**
     * 获取匹配文件的路径
     * @return 匹配文件的路径
     */
    public static String getConfigFilePath()
    {
        ResourceConfig resConf = new ResourceConfig();
       
        // web工程Clasess本地路径
        String webPath = resConf.getClass().getClassLoader().getResource("")
                .getPath();

        // 获得配置文件中的包名
        String packagepath = resConf.getClass().getPackage().toString();

        // 转换配置文件本地路径
        String packagePath = packagepath.substring(8).replace(".","/")+"/";
       
        String configFilePath = webPath+packagePath;
        return configFilePath;
    }
   
    /**
     * 获取class文件的绝对路径
     */
    public static String getClassPath(Class cls) {

        String path = null;
        java.net.URL url = getClassLocationURL(cls);
        if (url != null) {
            path = url.getPath();
            if ("jar".equalsIgnoreCase(url.getProtocol())) {
                try {
                    path = new java.net.URL(path).getPath();
                } catch (Exception e) {
                    e.printStackTrace();
                }

                int location = path.indexOf("!/");
                if (location != -1) {
                    path = path.substring(0, location);
                }
            }
            try {
                java.io.File file = new java.io.File(path);
                path = file.getCanonicalPath();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
        return pathChange(path);
    }
   
    /**
     * 获取class文件位置的URL
     */
    public static java.net.URL getClassLocationURL(final Class cls) {

        java.net.URL result = null;
        String clsAsResource = cls.getName().replace('.', '/').concat(".class");
        java.security.ProtectionDomain pd = cls.getProtectionDomain();
        /**
         * java.lang.Class contract does not specify if 'pd' can ever be null;
         * it is not the case for Sun's implementations, but guard against null
         * just in case:
         */
        if (pd != null) {
            java.security.CodeSource cs = pd.getCodeSource();
            /**
             * 'cs' can be null depending on the classloader behavior:
             */
            if (cs != null)
                result = cs.getLocation();
            if (result != null) {
                if ("file".equals(result.getProtocol())) {
                    try {
                        if (result.toExternalForm().endsWith(".jar")
                        || result.toExternalForm().endsWith(".zip"))
                            result = new java.net.URL("jar:".concat(
                                    result.toExternalForm()).concat("!/")
                            .concat(clsAsResource));
                        else if (new File(result.getFile()).isDirectory())
                            result = new java.net.URL(result, clsAsResource);
                    } catch (Exception ex) {
                        ex.printStackTrace();

                    }
                }
            }
        }

        if (result == null) {
            ClassLoader clsLoader = cls.getClassLoader();
            result = clsLoader != null ? clsLoader.getResource(clsAsResource)
            : ClassLoader.getSystemResource(clsAsResource);
        }
        return result;
    }
   
    /**
     * 将"\"转变"/",用于路径转换
     */
    public static String pathChange(String befstr) {
       
        StringBuffer afStr = new StringBuffer();
        for (int i = 0; i < befstr.length(); i++) {
            if ((befstr.charAt(i)) == '\\')
                afStr.append(String.valueOf('/'));
            else
                afStr.append(befstr.substring(i, i + 1));
        }
        return afStr.toString();
    }
   
    public static void main(String[] args)
    {
        System.out.println(getConfigFileContent("formattedfilter.xml"));
       // System.out.println(getClassPath(StringUtil.class));
    }


/**
 * XML文件解析成对象的接口实现类
 * @author chou
 * @version [版本,2008-07-26]
 * @see [相关类/方法]
 * @since [产品/模块版本]
 */
public class SQLFilterConfigManagerImpl implements SQLFilterConfigManager,
  InitializingBean {

 //  常量定义
 private static final String ATTRIBUTE_NAME = "name";
 private static final String ATTRIBUTE_PREFIXION = "prefixion";
 private static final String ATTRIBUTE_PROPERTY = "property";
 private static final String ATTRIBUTE_CONTENT = "content";
 private static final String FILENAME = "formattedfilter.xml";
 
 /** 配置文件对应的对象 */
 private Map data = null;

    /**
     * InitializingBean接口方法
     */
 public void afterPropertiesSet() throws Exception
 {
  loadXml();
 }

    /**
     * 将XML文件内容解析为对象
     *
     */
 private void loadXml()
 {
  Map ldata = new HashMap();
        InputStream fileStream = ResourceConfig.getConfigFileStream(FILENAME);
    try {
  
   //  获取配置文件的根结点
   Element root = OperateXML.getRoot(fileStream);

   // 获取根结点下的子结点
   List typeList = OperateXML.getSubNodes(root);
   if (typeList != null)
   {
    for (Iterator iterator = typeList.iterator(); iterator
      .hasNext();)
    {
     Element e = (Element) iterator.next();
     TypeConfig type = loadTypeConfig(e);
     if (type != null)
     {
      fillTypeConfig(type, e);
      ldata.put(type.getName(), type);
     }
    }
   }
   data = ldata;
  }
  finally
  {
   if (fileStream != null)
   {
    try
    {
     fileStream.close();
    }
    catch (IOException e)
    {
    }
   }
  }
 }

    /**
     * 生成并初始化TypeConfig对象
     * @param e XML结点元素
     * @return
     */
 private TypeConfig loadTypeConfig(Element e)
 {
  TypeConfig type = new TypeConfig();
  type.setName(e.attributeValue(ATTRIBUTE_NAME));
  return type;
 }
 
 private void fillTypeConfig(TypeConfig type, Element e)
 {
  List typeList = OperateXML.getSubNodes(e);
  if (typeList != null && typeList.size() > 0)
  {
   Set set = new HashSet();
   for (Iterator iterator = typeList.iterator(); iterator.hasNext();)
   {
    Element ef = (Element) iterator.next();
    FilterFormatter formatter = loadFilterFormatter(ef);
    if (formatter != null)
    {
     fillFilterFormatter(formatter, ef);
     set.add(formatter);
    }
   }
   type.setFomatters(set);
  }
 }
 
    /**
     * 给FilterFormatter对象设定属性值
     * @param formatter 要设定属性值的FilterFormatter对象
     * @param e XML文件结点元素
     */
 private void fillFilterFormatter(FilterFormatter formatter, Element e)
 {
  List typeList = OperateXML.getSubNodes(e);
  if (typeList != null && typeList.size() > 0)
  {
   Set set = new HashSet();
   for (Iterator iterator = typeList.iterator(); iterator.hasNext();)
   {
    Element ef = (Element) iterator.next();
    FormatterCondition formatterCondition = loadFormatterCondition(ef);
    if (formatterCondition != null)
    {
     fillFormatterCondition(formatterCondition, ef);
     set.add(formatterCondition);
    }
   }
   formatter.setConditions(set);
  }
 }
 
    /**
     * 给FormatterCondition对象设定属性值
     * @param formatter 要设定属性值的FormatterCondition对象
     * @param e XML文件结点元素
     */
 private void fillFormatterCondition(FormatterCondition formatterCondition, Element e)
 {
  List typeList = OperateXML.getSubNodes(e);
  if (typeList != null && typeList.size() > 0)
  {
   Set set = new HashSet();
   for (Iterator iterator = typeList.iterator(); iterator.hasNext();)
   {
    Element ef = (Element) iterator.next();
    Example eg = new Example();
    //eg.setExample(e.attributeValue(ATTRIBUTE_EXAMPLE));
    eg.setExample(ef.getText());
                set.add(eg);
   }
   formatterCondition.setExamples(set);
  }
 }
   
   /* private void fillExample(Example example, Element e)
    {
        example.setExample(e.getText());
    }*/
 
     /**
     * 生成并初始化FormatterCondition对象
     * @param e XML结点元素
     * @return
     */
 private FormatterCondition loadFormatterCondition(Element e)
 {
  FormatterCondition formatterCondition = new FormatterCondition();
  formatterCondition.setContent(e.attributeValue(ATTRIBUTE_CONTENT));
  return formatterCondition;
 }
 
    /**
     * 生成并初始化FilterFormatter对象
     * @param e XML结点元素
     * @return
     */
 private FilterFormatter loadFilterFormatter(Element e)
 {
  FilterFormatter formatter = new FilterFormatter();
  formatter.setPrefixion(e.attributeValue(ATTRIBUTE_PREFIXION));
  formatter.setProperty(e.attributeValue(ATTRIBUTE_PROPERTY));
  return formatter;
 }

    /**
     * 获取指定类型字段的过滤格式和例子的Map
     * @param type  字段类型
     * @return  封装了该字段类型的过滤格式和例子的Map
     */
 public TypeConfig getTypeConfig(String key) {
  // TODO Auto-generated method stub
  return (TypeConfig)data.get(key);
 }

}


/**
 * 文件操作类
 * @author chou
 * @version [版本号,2008-8-4]
 * @see [相关类/方法]
 * @since [产品/模块版本]
 */
public class OperateFile
{
    /**下载文件的编码格式*/
    private static final String FILECODING = "UTF-8";
   
    /**日志类*/
    private final Logger log = Logger.getLogger(getClass());
   
    private static final String CONTENT_TYPE = "application/octet-stream";
   
    /**
     * 下载文件
     * @param fileName 文件名称加路径
     * @throws IOException
     */
    public void downFile(String fileName, byte[] fileContent, HttpServletResponse res, HttpServletRequest req)
           throws BaseException
    {
        String downFileName = null;
        BufferedOutputStream bos = null;
       
        if (fileContent != null && fileContent.length >= 0  && res != null)
        {
            try
            {
                res.setContentType(CONTENT_TYPE);            
               
                if(fileName == null || fileName.equals("") == true)
                {
                    fileName = "anonymous";
                }
               
                downFileName = URLEncoder.encode(fileName, FILECODING);
               
                if (req.getHeader("User-Agent").indexOf("MSIE 5.5") != -1)
                {
                    res.setHeader("Content-disposition", "filename=" + downFileName);
                }
                else
                {
                    res.setHeader("Content-disposition", "attachment; filename=" + downFileName);
                }
                               
                byte[] buff = fileContent;

                bos = new BufferedOutputStream(res.getOutputStream());
                bos.write(buff);
               
            }
            catch (Exception e)
            {
                log.info("文件下载: " + e + " 文件下载异常!");
            }
            finally
            {
                if (bos != null)
                {
                    try
                    {
                        bos.flush();
                    }
                    catch (Exception e)
                    {
                        log.info("文件下载: " + e + " 文件下载异常!");                       
                    }
                    try
                    {
                        bos.close();
                    }
                    catch (Exception e)
                    {
                        log.info("文件下载: " + e + " 文件下载异常!");                       
                    }
                }
            }
        }
    }
}





public class OperateJson
{
    /**
     * 本方法提供将List集合中的convertObj对象转换到JSONArray集合中JSONObject,
     * 返回转换为JSONObject之后的JSONArray集合
     * @param convertObj List集合中对象的Class
     * @param list 需要转换为JSONArray集合的数据
     * @return
     * @throws IllegalAccessException
     * @throws IllegalArgumentException
     * @throws Exception
     */
    public JSONArray convertJSONArray(Class<?> convertObj, List list)
            throws IllegalArgumentException, IllegalAccessException
    {
        JSONArray array = new JSONArray();

        JSONObject jObj = null;
        Field[] fields = convertObj.getDeclaredFields();
        Object obj = null;
        for (Iterator iter = list.iterator(); iter.hasNext(); array.add(jObj))
        {
            obj = iter.next();
            jObj = new JSONObject();
            for (int i = 0; i < fields.length; i++)
            {
                jObj.element(fields[i].getName(), fields[i].get(obj));
            }
        }
        return array;
    }

    public JSONArray convertJSONArrayByField(Class<?> convertObj, List list)
            throws IllegalArgumentException, IllegalAccessException, SecurityException,
            NoSuchMethodException, InvocationTargetException
    {
        JSONArray array = new JSONArray();

        JSONObject jObj = null;
        Field[] fields = convertObj.getDeclaredFields();

        Object obj = null;
        for (Iterator iter = list.iterator(); iter.hasNext(); array.add(jObj))
        {
            obj = iter.next();
            jObj = new JSONObject();
            for (int i = 0; i < fields.length; i++)
            {
                String name = fields[i].getName();
                String xx = name.substring(0, 1);
                name = name.substring(1);
                name = xx.toUpperCase() + name;
                Method method = convertObj.getMethod("get" + name);
                jObj.element(fields[i].getName(), method.invoke(obj));
            }
        }
        return array;
    }

    /**
     * @param convertObj
     * @param list
     * @return
     * @throws IllegalArgumentException
     * @throws IllegalAccessException
     */
    public String toJSONString(Class<?> convertObj, List list) throws IllegalArgumentException,
            IllegalAccessException
    {

        Field[] fields = convertObj.getFields();
        Object obj = null;
        StringBuffer value = new StringBuffer("[");
        for (Iterator iter = list.iterator(); iter.hasNext();)
        {
            obj = iter.next();
            for (int i = 0; i < fields.length; i++)
            {
                if (i != 0)
                {
                    value.append(",{");
                }
                else
                {
                    value.append("{");
                }

                value.append("'" + fields[i].getName() + "':'" + fields[i].get(obj) + "',");
            }
        }
        value.append("]");
        return value.toString();
    }

    /**
     * 该方法把数组对象转换成jsonObj形式的字符串
     * @param arrayObj
     * @return
     */
    public static String toJSONString(String[][] arrayObj)
    {
        StringBuffer value = new StringBuffer("[");

        for (int i = 0; i < arrayObj.length; i++)
        {
            String[] field = arrayObj[i];
            if (i != 0)
            {
                value.append(",{");
            }
            else
            {
                value.append("{");
            }

            value.append("'id':'" + field[0] + "',");
            value.append("'name':'" + field[1] + "',");
            value.append("'descn':'" + field[2] + "'");
            value.append("}");
        }
        value.append("]");
        return value.toString();
    }

    /**
     * @param arrayObj
     * @return
     */
    public static String convertJSONArray(String[][] arrayObj)
    {
        JSONArray array = new JSONArray();
        JSONObject jObj = null;
        for (int i = 0; i < arrayObj.length; i++)
        {
            String[] field = arrayObj[i];
            jObj = new JSONObject();
            jObj.element("id", field[0]);
            jObj.element("name", field[1]);
            jObj.element("descn", field[2]);
            array.add(jObj);
        }
        return array.toString();
    }

    /**
     * 通过List对象获得公告的JSON对象
     * @param list
     * @param loginUser 当前登陆用户编号
     * @return JSONObject
     */
    public JSONObject convertJSONBulletin(List list, User loginUser, int count)
    {
        // 创建一个JSONArray对象
        JSONArray array = new JSONArray();
        // 创建一个保存公告的对象
        JSONObject jObj = null;
        JSONObject totle = new JSONObject();

        // 格式化时间格式
        SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss");

        // 确定集合的大小
        int size = list.size();

        // 遍历List对象

        for (int i = 0; i < size; i++)
        {
            jObj = new JSONObject();
            Bulletins bulletins = (Bulletins) list.get(i);

            jObj.element("newsID", bulletins.getNewsId()); // 设置公告编号
            jObj.element("status", bulletins.getNewsStatus()); // 设置公告的状态
            jObj.element("newsType", bulletins.getNewsType()); // 设置公告的类型
            jObj.element("newTitle", bulletins.getNewsTitle()); // 设置公告标题
            jObj.element("newsGroup", bulletins.getGroupName()); // 设置公告的归属
            jObj.element("startDate", sdf.format(bulletins.getBeginTime()).substring(0, 10)); // 设置公告开始时间
            jObj.element("endDate", sdf.format(bulletins.getEndTime()).substring(0, 10)); // 设置公告结束时间
            jObj.element("popType", bulletins.getPopType()); // 设置公告的弹出方式
            jObj.element("groupCode", bulletins.getFGroupcode()); // 设置公告的归属部门编号
            jObj.element("userId", loginUser.getId()); // 设置公告创建人编号

            array.add(jObj);
        }
        totle.accumulate("totalRecord", count);
        totle.accumulate("records", array);
        return totle;
    }

    public static void main(String[] args)
    {

        String[][] array = new String[10][3];

        for (int i = 0; i < array.length; i++)
        {
            array[i][0] = i + "";
            array[i][1] = "name " + i;
            array[i][2] = "descn " + i;
        }
        long jsona = System.currentTimeMillis();
        String json1 = OperateJson.convertJSONArray(array);
        long jsonb = System.currentTimeMillis();
        System.out.println(json1);
        System.out.println("===========" + (jsonb - jsona));

        long a = System.currentTimeMillis();
        String c = OperateJson.toJSONString(array);
        long b = System.currentTimeMillis();

        System.out.println(c);
        System.out.println("===========" + (b - a));
    }

}