stringutils.java

来自「短信系统SMS:支持普通短信、长短信和wap push短信的发送。」· Java 代码 · 共 380 行

JAVA
380
字号
package com.ekun.common.util;

/**
 * <p>Title: </p>
 *
 * <p>Description: </p>
 *
 * <p>Copyright: Copyright (c) 2006</p>
 *
 * <p>Company: </p>
 *
 * @author ekun
 * @version 1.0
 */

import java.io.*;
import java.util.*;
import java.text.SimpleDateFormat;

public class StringUtils
{
  /**
   * 将byte数组转换为表示16进制值的字符串,
   * 如:byte[]{8,18}转换为:0813,
   * 和public static byte[] hexStr2ByteArr(String strIn)
   * 互为可逆的转换过程
   * @param arrB 需要转换的byte数组
   * @return 转换后的字符串
   * @throws Exception 本方法不处理任何异常,所有异常全部抛出
   */
  public static String byteArr2HexStr(byte[] arrB) throws Exception
  {
    int iLen = arrB.length;
    //每个byte用两个字符才能表示,所以字符串的长度是数组长度的两倍
    StringBuffer sb = new StringBuffer(iLen * 2);
    for (int i = 0; i < iLen; i++)
    {
      int intTmp = arrB[i];
      //把负数转换为正数
      while (intTmp < 0)
      {
        intTmp = intTmp + 256;
      }
      //小于0F的数需要在前面补0
      if (intTmp < 16)
      {
        sb.append("0");
      }
      sb.append(Integer.toString(intTmp, 16));
    }
    return sb.toString();
  }

  /**
   * 将表示16进制值的字符串转换为byte数组,
   * 和public static String byteArr2HexStr(byte[] arrB)
   * 互为可逆的转换过程
   * @param strIn 需要转换的字符串
   * @return 转换后的byte数组
   * @throws Exception 本方法不处理任何异常,所有异常全部抛出
   */
  public static byte[] hexStr2ByteArr(String strIn) throws Exception
  {
    byte[] arrB = strIn.getBytes();
    int iLen = arrB.length;
    //两个字符表示一个字节,所以字节数组长度是字符串长度除以2
    byte[] arrOut = new byte[iLen / 2];
    for (int i = 0; i < iLen; i = i + 2)
    {
      String strTmp = new String(arrB, i, 2);
      arrOut[i / 2] = (byte) Integer.parseInt(strTmp, 16);
    }
    return arrOut;
  }

  /**
   *@param str the string need to be parsed
   *@param delim the delimiter to seperate
   */
  public static String[] parseToArray(String str, String delim)
  {
    ArrayList arr = new ArrayList();
    StringTokenizer st = new StringTokenizer(str, delim);
    while (st.hasMoreTokens())
    {
      arr.add(st.nextToken());
    }
    String[] ret = new String[arr.size()];
    for (int i = 0; i < arr.size(); i++)
    {
      ret[i] = (String) arr.get(i);
    }
    return ret;
  }

  /**
           replace a old substring with rep in str
           @param str the string need to be replaced
           @param old the string need to be removed
           @param rep the string to be inserted
           @return string replaced
   */
  public static String replace(String str, String old, String rep)
  {
    if ( (str == null) || (old == null) || (rep == null))
    { //if one is null return ""
      return "";
    }
    int index = str.indexOf(old);
    if ( (index < 0) || old.equals(""))
    { //if no old string found or nothing to replace,return the origin
      return str;
    }
    StringBuffer strBuf = new StringBuffer(str);
    while (index >= 0)
    { //found old part
      strBuf.delete(index, index + old.length());
      strBuf.insert(index, rep);
      index = strBuf.toString().indexOf(old);
    }
    return strBuf.toString();
  }

  /**
   * get the string format of a date precise to millisecond
   * @param date the input date
   * @return the string
   */
  public static String getTimeString(Date date)
  {
    String timePattren = "yyyyMMddHHmmssSSS";
    return toString(date, timePattren);
  }

  /**
    convert a date to string according to the format pattern
   * @param date input date
   * @param pattern format pattern
   * @return the formated string
   */
  public static String toString(Date date, String pattern)
  {
    SimpleDateFormat fo = new SimpleDateFormat(pattern);
    return fo.format(date);
  }

  /**
   * Deal with null strings converting them to "" instead.  It also
   * invokes String.trim() on the output.
   *
   * @param foo A String.
   * @return A String.
   */
  public static final String makeString(String foo)
  {
    return (foo == null ? "" : foo.trim());
  }

  public static boolean strIsEmpty(String str)
  {
    if ( (null == str) || "".equals(str))
      return true;
    return false;
  }

  public static boolean strTrimIsEmpty(String str)
  {
    if ( (str == null) || (str.trim().equals("")))
      return true;
    else
      return false;
  }

  /**
   * Returns the output of printStackTrace as a String.
   *
   * @param e A Throwable.
   * @return A String.
   */
  public static final String stackTrace(Throwable e)
  {
    String foo = null;
    try
    {
      // And show the Error Screen.
      ByteArrayOutputStream buf = new ByteArrayOutputStream();
      e.printStackTrace(new PrintWriter(buf, true));
      foo = buf.toString();
    }
    catch (Exception f)
    {
      // Do nothing.
    }
    return foo;
  }

  /**
   * Returns the output of printStackTrace as a String.
   *
   * @param e A Throwable.
   * @param addPre a boolean to add HTML <pre> tags around the stacktrace
   * @return A String.
   */
  public static final String stackTrace(Throwable e, boolean addPre)
  {
    if (addPre)
    {
      return "<pre>" + stackTrace(e) + "</pre>";
    }
    else
    {
      return stackTrace(e);
    }
  }

  /**
   * Compares two Strings, returns true if their values are the
   * same.
   *
   * @param s1 The first string.
   * @param s2 The second string.
   * @return True if the values of both strings are the same.
   */
  public static boolean equals(String s1, String s2)
  {
    if (s1 == null)
    {
      return (s2 == null);
    }
    else if (s2 == null)
    {
      // s1 is not null
      return false;
    }
    else
    {
      return s1.equals(s2);
    }
  }

  /**
   * Splits the provided CSV text into a list.
   *
   * @param text      The CSV list of values to split apart.
   * @param separator The separator character.
   * @return          The list of values.
   */
  public static String[] split(String text, String separator)
  {
    StringTokenizer st = new StringTokenizer(text, separator);
    String[] values = new String[st.countTokens()];
    int pos = 0;
    while (st.hasMoreTokens())
    {
      values[pos++] = st.nextToken();
    }
    return values;
  }

  public static String ISOtoGBK(String str)
  {

    byte[] by = null;
    try
    {
      by = str.getBytes("ISO-8859-1");
    }
    catch (UnsupportedEncodingException ex)
    {
      ex.printStackTrace();
      return str;
    }
    try
    {
      String a = new String(by, "GBK");
      return a;
    }
    catch (UnsupportedEncodingException ex1)
    {
      ex1.printStackTrace();
      return str;
    }
  }
  /**
   * 将按GBK编码读取的字符串重新编码成系统默认编码.
   * @param source 带转换的字符串
   * @return 以系统默认编码的字符串。
   */
  public static String gbkToLocal(String source)
  {
    String sysEnc = System.getProperty("file.encoding");
    String result = "";
    if (source != null)
    {
      try
      {
        System.out.println("gbkToLocal---- changed before(GBK):" +
                           source);
        result = new String(source.getBytes("GBK"), sysEnc);
        System.out.println("gbkToLocal---- changed(" + sysEnc + "):" +
                           result);
      }
      catch (Exception e)
      {
        e.printStackTrace();
      }
    }
    return result;
  }
  /**
   * trim the string even when it's null
   * @param str the string need to be trimmed
   * @return the trimmed string
   */
  public static String trim(String str)
  {
    if (str == null)
    {
      return "";
    }
    return str.trim();
  }

  /**
   * 将带有格式的字符串转换成HTML方式
   * @param origine
   * @return
   */
  public static String convert2Html(String origine)
  {
    String outStr = null;
    if (origine != null)
    {
      String tmp = StringUtils.replace(origine, ">", "&gt;");
      String tmp2 = StringUtils.replace(tmp, "<", "&lt;");
      String tmp3 = StringUtils.replace(tmp2, " ", "&nbsp;");

      String tmp4 = StringUtils.replace(tmp3, "\r\n", "<br>");

      outStr = tmp4;
    }
    else
    {
      outStr = "";
    }
    return outStr;
  }
  /**
   * sms字符转换
   * @param content byte[]
   * @param msgFormat int
   * @return String
   */
  public static String smsParse(byte[] content, int msgFormat)
  {
    try
    {
      switch (msgFormat)
      {
        case 0: // ascii
          return new String(new String(content, "ASCII").getBytes("GBK"));
        case 8:
          return new String(new String(content,
                            "iso-10646-ucs-2").getBytes("GBK"));
        case 15:
          return new String(new String(content, "GBK").getBytes("GBK"));
        case 3:
        case 4:
        default:
          return null;
      }
    }
    catch (Exception ex)
    {
      ex.printStackTrace();
      return null;
    }
  }
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?