• 公共类


      1 /**功能说明   
      2  * @param 公共方法
      3  * @author 
      4  * @since 2013-4-15 下午02:04:56
      5  */
      6 package com.mall.common;
      7 
      8 import java.io.UnsupportedEncodingException;
      9 import java.lang.reflect.Array;
     10 import java.text.DecimalFormat;
     11 import java.text.SimpleDateFormat;
     12 import java.util.Collection;
     13 import java.util.Date;
     14 import java.util.Map;
     15 import java.util.StringTokenizer;
     16 
     17 import org.apache.log4j.Logger;
     18 
     19 import sun.misc.BASE64Decoder;
     20 
     21 public class StringUtils {
     22     private static Logger log=Logger.getLogger(StringUtils.class);
     23     
     24     public static final String KEYWORD_IMPORT = "会员批量导入已经成功!";
     25 
     26     public static final String ALLOWED_CHARS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.!~*'()";
     27 
     28     /**
     29      * 转码
     30      * @param input
     31      * @return
     32      */
     33     public static String encodeURIComponent(String input) {
     34         if (StringUtils.isEmpty(input)) {
     35             return input;
     36         }
     37 
     38         int l = input.length();
     39         StringBuilder o = new StringBuilder(l * 3);
     40         try {
     41             for (int i = 0; i < l; i++) {
     42                 String e = input.substring(i, i + 1);
     43                 if (ALLOWED_CHARS.indexOf(e) == -1) {
     44                     byte[] b = e.getBytes("utf-8");
     45                     o.append(getHex(b));
     46                     continue;
     47                 }
     48                 o.append(e);
     49             }
     50             return o.toString();
     51         } catch (UnsupportedEncodingException e) {
     52             log.error(e.getMessage());
     53         }
     54         return input;
     55     }
     56 
     57     /**
     58      * 解码
     59      * @param encodedURI
     60      * @return
     61      */
     62     public static String decodeURIComponent(String encodedURI) {
     63         char actualChar;
     64 
     65         StringBuffer buffer = new StringBuffer();
     66 
     67         int bytePattern, sumb = 0;
     68 
     69         for (int i = 0, more = -1; i < encodedURI.length(); i++) {
     70             actualChar = encodedURI.charAt(i);
     71 
     72             switch (actualChar) {
     73             case '%': {
     74                 actualChar = encodedURI.charAt(++i);
     75                 int hb = (Character.isDigit(actualChar) ? actualChar - '0'
     76                         : 10 + Character.toLowerCase(actualChar) - 'a') & 0xF;
     77                 actualChar = encodedURI.charAt(++i);
     78                 int lb = (Character.isDigit(actualChar) ? actualChar - '0'
     79                         : 10 + Character.toLowerCase(actualChar) - 'a') & 0xF;
     80                 bytePattern = (hb << 4) | lb;
     81                 break;
     82             }
     83             case '+': {
     84                 bytePattern = ' ';
     85                 break;
     86             }
     87             default: {
     88                 bytePattern = actualChar;
     89             }
     90             }
     91 
     92             if ((bytePattern & 0xc0) == 0x80) { // 10xxxxxx
     93                 sumb = (sumb << 6) | (bytePattern & 0x3f);
     94                 if (--more == 0)
     95                     buffer.append((char) sumb);
     96             } else if ((bytePattern & 0x80) == 0x00) { // 0xxxxxxx
     97                 buffer.append((char) bytePattern);
     98             } else if ((bytePattern & 0xe0) == 0xc0) { // 110xxxxx
     99                 sumb = bytePattern & 0x1f;
    100                 more = 1;
    101             } else if ((bytePattern & 0xf0) == 0xe0) { // 1110xxxx
    102                 sumb = bytePattern & 0x0f;
    103                 more = 2;
    104             } else if ((bytePattern & 0xf8) == 0xf0) { // 11110xxx
    105                 sumb = bytePattern & 0x07;
    106                 more = 3;
    107             } else if ((bytePattern & 0xfc) == 0xf8) { // 111110xx
    108                 sumb = bytePattern & 0x03;
    109                 more = 4;
    110             } else { // 1111110x
    111                 sumb = bytePattern & 0x01;
    112                 more = 5;
    113             }
    114         }
    115         return buffer.toString();
    116     }
    117 
    118     private static String getHex(byte buf[]) {
    119         StringBuilder o = new StringBuilder(buf.length * 3);
    120         for (int i = 0; i < buf.length; i++) {
    121             int n = (int) buf[i] & 0xff;
    122             o.append("%");
    123             if (n < 0x10) {
    124                 o.append("0");
    125             }
    126             o.append(Long.toString(n, 16).toUpperCase());
    127         }
    128         return o.toString();
    129     }
    130 
    131     /**
    132      * 判断某个对象是否为空 集合类、数组做特殊处理
    133      * 
    134      * @param obj
    135      * @return 如为空,返回true,否则false
    136      * @author YZH
    137      */
    138     @SuppressWarnings("unchecked")
    139     public static boolean isEmpty(Object obj) {
    140         if (obj == null)
    141             return true;
    142 
    143         // 如果不为null,需要处理几种特殊对象类型
    144         if (obj instanceof String) {
    145             return obj.equals("");
    146         } else if (obj instanceof Collection) {
    147             // 对象为集合
    148             Collection coll = (Collection) obj;
    149             return coll.size() == 0;
    150         } else if (obj instanceof Map) {
    151             // 对象为Map
    152             Map map = (Map) obj;
    153             return map.size() == 0;
    154         } else if (obj.getClass().isArray()) {
    155             // 对象为数组
    156             return Array.getLength(obj) == 0;
    157         } else {
    158             // 其他类型,只要不为null,即不为empty
    159             return false;
    160         }
    161     }
    162 
    163     /**
    164      * 转码
    165      * @param str
    166      * @return
    167      */
    168     public static String encodeBase64(String str){
    169         if (str == null){ 
    170             return null; 
    171         }else{
    172             return (new sun.misc.BASE64Encoder()).encode(str.getBytes() ); 
    173         }
    174     }
    175     
    176     /**
    177      * 解码
    178      * @param args
    179      */
    180     public static String  decodeBase64(String str){
    181         if (str == null) {
    182             return null;
    183         }else{
    184             BASE64Decoder decoder = new BASE64Decoder(); 
    185             try {
    186                 byte[] b = decoder.decodeBuffer(str); 
    187                 return new String(b); 
    188             } catch (Exception e) {
    189                 e.printStackTrace();
    190                 return null; 
    191             }
    192         }
    193     }
    194 
    195     /**
    196      * 使用StringTokenizer类将字符串按分隔符转换成字符数组
    197      * @param string 字符串 
    198      * @param divisionChar 分隔符
    199      * @return 字符串数组
    200      * @see [类、类#方法、类#成员]
    201      */
    202     public static String[] stringAnalytical(String string, String divisionChar)
    203     {
    204         int i = 0;
    205         StringTokenizer tokenizer = new StringTokenizer(string, divisionChar);
    206         
    207         String[] str = new String[tokenizer.countTokens()];
    208         
    209         while (tokenizer.hasMoreTokens())
    210         {
    211             str[i] = new String();
    212             str[i] = tokenizer.nextToken();
    213             i++;
    214         }
    215         
    216         return str;
    217     }
    218     
    219     /**
    220      * 字符串解析,不使用StringTokenizer类和java.lang.String的split()方法
    221      * 将字符串根据分割符转换成字符串数组
    222      * @param string 字符串
    223      * @param c 分隔符
    224      * @return 解析后的字符串数组
    225      */
    226     public static String[] stringAnalytical(String string, char c)
    227     {
    228         //字符串中分隔符的个数
    229         int count = 0;
    230         
    231         //如果不含分割符则返回字符本身
    232         if (string.indexOf(c) == -1)
    233         {
    234             return new String[]{string};
    235         }
    236         
    237         char[] cs = string.toCharArray();
    238         
    239         //过滤掉第一个和最后一个是分隔符的情况
    240         for (int i = 1; i < cs.length -1; i++)
    241         {
    242             if (cs[i] == c)
    243             {
    244                 count++; //得到分隔符的个数
    245             }
    246         }
    247         
    248         String[] strArray = new String[count + 1];
    249         int k = 0, j = 0;
    250         String str = string;
    251         
    252         //去掉第一个字符是分隔符的情况
    253         if ((k = str.indexOf(c)) == 0)
    254         {
    255             str = string.substring(k + 1);
    256         }
    257         
    258         //检测是否包含分割符,如果不含则返回字符串
    259         if (str.indexOf(c) == -1)
    260         {
    261             return new String[]{str};
    262         }
    263         
    264         while ((k = str.indexOf(c)) != -1)
    265         {
    266             strArray[j++] = str.substring(0, k);
    267             str = str.substring(k + 1);
    268             if ((k = str.indexOf(c)) == -1 && str.length() > 0)
    269             {
    270                 strArray[j++] = str.substring(0);
    271             }
    272         }
    273         
    274         return strArray;
    275     }
    276 
    277     /**
    278      * 去除null以及空格串
    279      * @return:
    280      * @author: YZH
    281      */
    282     public static String noNull(Object s) {
    283         if (s == null)
    284             return "";
    285         else
    286             return s.toString().trim();
    287     }
    288     
    289     /**
    290      * 
    291      * {将文件名中的汉字转为UTF8编码的串,以便下载时能正确显示另存的文件名}
    292      * @param s 原文件名
    293      * @return  重新编码后的文件名
    294      * @author: YZH
    295      */
    296     public static String toUtf8String(String s) {
    297         StringBuffer sb = new StringBuffer();
    298         for (int i = 0; i < s.length(); i++) {
    299             char c = s.charAt(i);
    300             if ((c >= 0) && (c <= 255)) {
    301                 sb.append(c);
    302             }
    303             else {
    304                 byte[] b;
    305 
    306                 try {
    307                     b = Character.toString(c).getBytes("UTF-8");
    308                 }
    309                 catch (Exception ex) {
    310                     System.out.println(ex);
    311                     b = new byte[0];
    312                 }
    313                 for (int j = 0; j < b.length; j++) {
    314                     int k = b[j];
    315                     if (k < 0) {
    316                         k += 256;
    317                     }
    318                     sb.append("%" + Integer.toHexString(k).toUpperCase());
    319                 }
    320             }
    321         }
    322         return sb.toString();
    323     }
    324 
    325     public static boolean arryContain(String[]arr,String s2){
    326         for(int i=0;i<arr.length;i++){
    327             String si=arr[i];
    328             if(si.equals(s2)){
    329                 return true;
    330             }
    331         }
    332         return false;
    333     }
    334     //格式化时间
    335     public static String formatNum(Object num,String pattern){
    336         DecimalFormat df = new DecimalFormat(pattern);
    337         String db = df.format(num);
    338         return db;
    339     }
    340     /**
    341      * 
    342      * @param 要四舍五入的数(0.045)
    343      * @param precision(2) 保留位数 0.05
    344      * @return
    345      */
    346     public static String round(double val, int precision) {  
    347         Double ret = null;  
    348         try {  
    349             double factor = Math.pow(10, precision);  
    350             ret = Math.floor(val * factor + 0.5) / factor;  
    351             return ret+"";
    352         } catch (Exception e) {  
    353             e.printStackTrace();  
    354             return val+"";
    355         }   
    356     }  
    357     
    358     //字符串转换成日期(包括年月日时分秒)
    359     public static Date stringToDateTime(String str,String pattern){
    360         SimpleDateFormat sdf=new SimpleDateFormat(pattern);
    361         Date dt=null;
    362         try {
    363             dt = sdf.parse(str);
    364             return dt;
    365         } catch (Exception e) {
    366             e.printStackTrace();
    367             return null;
    368         }
    369     }
    370 
    371     public static String checkTips(String tips) {
    372         StringBuffer sb = new StringBuffer();
    373         sb.append("<script type="text/javascript">").append("alert('").append(tips)
    374                 .append("');window.history.back();").append("</script>");
    375         return sb.toString();
    376     }
    377     
    378     public static void main(String[]args){
    379          String result=StringUtils.round(0.003d, 2);
    380          String a = StringUtils.encodeBase64("aaaaa");
    381          String b = StringUtils.decodeBase64(a);
    382          System.out.println(result+"==="+a+"==="+b);
    383     }
    384 }
  • 相关阅读:
    CF 852E--Casinos and travel(思维)
    Sigma Sigma Cnk --- CF 575H
    CF1316E-Team Building(dp+贪心)
    cf1316C--Primitive Primes
    cf1323--Count Subrectangles(思维)
    CF252B--鸽巢原理
    HDU3652--容斥+数位dp
    DP--HDU4571(Floyd+dp)
    HDU4219--Randomization?(树形概率DP)
    HDU5945--Fxx and Game dp(单调队列优化)
  • 原文地址:https://www.cnblogs.com/lixin890808/p/3904760.html
Copyright © 2020-2023  润新知