码迷,mamicode.com
首页 > 编程语言 > 详细

java综合工具类

时间:2014-11-12 22:57:26      阅读:304      评论:0      收藏:0      [点我收藏+]

标签:style   blog   io   color   ar   os   java   sp   for   

  1 package com.gootrip.util;
  2 
  3 /**
  4  * 此类中收集Java编程中WEB开发常用到的一些工具。
  5  * 为避免生成此类的实例,构造方法被申明为private类型的。
  6  * @author 
  7  */
  8 import java.io.IOException;
  9 import java.io.StringReader;
 10 import java.io.UnsupportedEncodingException;
 11 import java.security.MessageDigest;
 12 import java.util.Date;
 13 
 14 
 15 public class CTool {
 16     /**
 17      * 私有构造方法,防止类的实例化,因为工具类不需要实例化。
 18      */
 19     private CTool() {
 20     }
 21 
 22     /**
 23       <pre>
 24      * 例:
 25      * String strVal="This is a dog";
 26      * String strResult=CTools.replace(strVal,"dog","cat");
 27      * 结果:
 28      * strResult equals "This is cat"
 29      *
 30      * @param strSrc 要进行替换操作的字符串
 31      * @param strOld 要查找的字符串
 32      * @param strNew 要替换的字符串
 33      * @return 替换后的字符串
 34       <pre>
 35      */
 36     public static final String replace(String strSrc, String strOld,
 37                                        String strNew) {
 38         if (strSrc == null || strOld == null || strNew == null)
 39             return "";
 40 
 41         int i = 0;
 42         
 43         if (strOld.equals(strNew)) //避免新旧字符一样产生死循环
 44             return strSrc;
 45         
 46         if ((i = strSrc.indexOf(strOld, i)) >= 0) {
 47             char[] arr_cSrc = strSrc.toCharArray();
 48             char[] arr_cNew = strNew.toCharArray();
 49 
 50             int intOldLen = strOld.length();
 51             StringBuffer buf = new StringBuffer(arr_cSrc.length);
 52             buf.append(arr_cSrc, 0, i).append(arr_cNew);
 53 
 54             i += intOldLen;
 55             int j = i;
 56 
 57             while ((i = strSrc.indexOf(strOld, i)) > 0) {
 58                 buf.append(arr_cSrc, j, i - j).append(arr_cNew);
 59                 i += intOldLen;
 60                 j = i;
 61             }
 62 
 63             buf.append(arr_cSrc, j, arr_cSrc.length - j);
 64 
 65             return buf.toString();
 66         }
 67 
 68         return strSrc;
 69     }
 70 
 71     /**
 72      * 用于将字符串中的特殊字符转换成Web页中可以安全显示的字符串
 73      * 可对表单数据据进行处理对一些页面特殊字符进行处理如‘<‘,‘>‘,‘"‘,‘‘‘,‘&‘
 74      * @param strSrc 要进行替换操作的字符串
 75      * @return 替换特殊字符后的字符串
 76      * @since  1.0
 77      */
 78 
 79     public static String htmlEncode(String strSrc) {
 80         if (strSrc == null)
 81             return "";
 82 
 83         char[] arr_cSrc = strSrc.toCharArray();
 84         StringBuffer buf = new StringBuffer(arr_cSrc.length);
 85         char ch;
 86 
 87         for (int i = 0; i < arr_cSrc.length; i++) {
 88             ch = arr_cSrc[i];
 89 
 90             if (ch == ‘<‘)
 91                 buf.append("&lt;");
 92             else if (ch == ‘>‘)
 93                 buf.append("&gt;");
 94             else if (ch == ‘"‘)
 95                 buf.append("&quot;");
 96             else if (ch == ‘\‘‘)
 97                 buf.append("&#039;");
 98             else if (ch == ‘&‘)
 99                 buf.append("&amp;");
100             else
101                 buf.append(ch);
102         }
103 
104         return buf.toString();
105     }
106 
107     /**
108      * 用于将字符串中的特殊字符转换成Web页中可以安全显示的字符串
109      * 可对表单数据据进行处理对一些页面特殊字符进行处理如‘<‘,‘>‘,‘"‘,‘‘‘,‘&‘
110      * @param strSrc 要进行替换操作的字符串
111      * @param quotes 为0时单引号和双引号都替换,为1时不替换单引号,为2时不替换双引号,为3时单引号和双引号都不替换
112      * @return 替换特殊字符后的字符串
113      * @since  1.0
114      */
115     public static String htmlEncode(String strSrc, int quotes) {
116 
117         if (strSrc == null)
118             return "";
119         if (quotes == 0) {
120             return htmlEncode(strSrc);
121         }
122 
123         char[] arr_cSrc = strSrc.toCharArray();
124         StringBuffer buf = new StringBuffer(arr_cSrc.length);
125         char ch;
126 
127         for (int i = 0; i < arr_cSrc.length; i++) {
128             ch = arr_cSrc[i];
129             if (ch == ‘<‘)
130                 buf.append("&lt;");
131             else if (ch == ‘>‘)
132                 buf.append("&gt;");
133             else if (ch == ‘"‘ && quotes == 1)
134                 buf.append("&quot;");
135             else if (ch == ‘\‘‘ && quotes == 2)
136                 buf.append("&#039;");
137             else if (ch == ‘&‘)
138                 buf.append("&amp;");
139             else
140                 buf.append(ch);
141         }
142 
143         return buf.toString();
144     }
145 
146     /**
147      * 和htmlEncode正好相反
148      * @param strSrc 要进行转换的字符串
149      * @return 转换后的字符串
150      * @since  1.0
151      */
152     public static String htmlDecode(String strSrc) {
153         if (strSrc == null)
154             return "";
155         strSrc = strSrc.replaceAll("&lt;", "<");
156         strSrc = strSrc.replaceAll("&gt;", ">");
157         strSrc = strSrc.replaceAll("&quot;", "\"");
158         strSrc = strSrc.replaceAll("&#039;", "‘");
159         strSrc = strSrc.replaceAll("&amp;", "&");
160         return strSrc;
161     }
162 
163     /**
164      * 在将数据存入数据库前转换
165      * @param strVal 要转换的字符串
166      * @return 从“ISO8859_1”到“GBK”得到的字符串
167      * @since  1.0
168      */
169     public static String toChinese(String strVal) {
170         try {
171             if (strVal == null) {
172                 return "";
173             } else {
174                 strVal = strVal.trim();
175                 strVal = new String(strVal.getBytes("ISO8859_1"), "GBK");
176                 return strVal;
177             }
178         } catch (Exception exp) {
179             return "";
180         }
181     }
182     /**
183      * 编码转换 从UTF-8到GBK
184      * @param strVal
185      * @return
186      */
187     public static String toGBK(String strVal) {
188         try {
189             if (strVal == null) {
190                 return "";
191             } else {
192                 strVal = strVal.trim();
193                 strVal = new String(strVal.getBytes("UTF-8"), "GBK");
194                 return strVal;
195             }
196         } catch (Exception exp) {
197             return "";
198         }
199     }
200 
201     /**
202      * 将数据从数据库中取出后转换   *
203      * @param strVal 要转换的字符串
204      * @return 从“GBK”到“ISO8859_1”得到的字符串
205      * @since  1.0
206      */
207     public static String toISO(String strVal) {
208         try {
209             if (strVal == null) {
210                 return "";
211             } else {
212                 strVal = new String(strVal.getBytes("GBK"), "ISO8859_1");
213                 return strVal;
214             }
215         } catch (Exception exp) {
216             return "";
217         }
218     }
219     public static String gbk2UTF8(String strVal) {
220         try {
221             if (strVal == null) {
222                 return "";
223             } else {
224                 strVal = new String(strVal.getBytes("GBK"), "UTF-8");
225                 return strVal;
226             }
227         } catch (Exception exp) {
228             return "";
229         }
230     }
231     public static String ISO2UTF8(String strVal) {
232        try {
233            if (strVal == null) {
234                return "";
235            } else {
236                strVal = new String(strVal.getBytes("ISO-8859-1"), "UTF-8");
237                return strVal;
238            }
239        } catch (Exception exp) {
240            return "";
241        }
242    }
243    public static String UTF82ISO(String strVal) {
244        try {
245            if (strVal == null) {
246                return "";
247            } else {
248                strVal = new String(strVal.getBytes("UTF-8"), "ISO-8859-1");
249                return strVal;
250            }
251        } catch (Exception exp) {
252            return "";
253        }
254    }
255 
256 
257 
258     /**
259      *显示大文本块处理(将字符集转成ISO)
260      *@deprecated
261      *@param str 要进行转换的字符串
262      *@return 转换成html可以正常显示的字符串
263      */
264     public static String toISOHtml(String str) {
265         return toISO(htmlDecode(null2Blank((str))));
266     }
267 
268     /**
269      *实际处理 return toChineseNoReplace(null2Blank(str));
270      *主要应用于老牛的信息发布
271      *@param str 要进行处理的字符串
272      *@return 转换后的字符串
273      *@see fs_com.utils.CTools#toChinese
274      *@see fs_com.utils.CTools#null2Blank
275      */
276     public static String toChineseAndHtmlEncode(String str, int quotes) {
277         return htmlEncode(toChinese(str), quotes);
278     }
279 
280     /**
281      *把null值和""值转换成&nbsp;
282      *主要应用于页面表格格的显示
283      *@param str 要进行处理的字符串
284      *@return 转换后的字符串
285      */
286     public static String str4Table(String str) {
287         if (str == null)
288             return "&nbsp;";
289         else if (str.equals(""))
290             return "&nbsp;";
291         else
292             return str;
293     }
294 
295     /**
296      * String型变量转换成int型变量
297      * @param str 要进行转换的字符串
298      * @return intVal 如果str不可以转换成int型数据,返回-1表示异常,否则返回转换后的值
299      * @since  1.0
300      */
301     public static int str2Int(String str) {
302         int intVal;
303 
304         try {
305             intVal = Integer.parseInt(str);
306         } catch (Exception e) {
307             intVal = 0;
308         }
309 
310         return intVal;
311     }
312 
313     public static double str2Double(String str) {
314         double dVal = 0;
315 
316         try {
317             dVal = Double.parseDouble(str);
318         } catch (Exception e) {
319             dVal = 0;
320         }
321 
322         return dVal;
323     }
324 
325 
326     public static long str2Long(String str) {
327         long longVal = 0;
328 
329         try {
330             longVal = Long.parseLong(str);
331         } catch (Exception e) {
332             longVal = 0;
333         }
334 
335         return longVal;
336     }
337 
338     public static float stringToFloat(String floatstr) {
339         Float floatee;
340         floatee = Float.valueOf(floatstr);
341         return floatee.floatValue();
342     }
343 
344     //change the float type to the string type
345     public static String floatToString(float value) {
346         Float floatee = new Float(value);
347         return floatee.toString();
348     }
349 
350     /**
351      *int型变量转换成String型变量
352      *@param intVal 要进行转换的整数
353      *@return str 如果intVal不可以转换成String型数据,返回空值表示异常,否则返回转换后的值
354      */
355     /**
356      *int型变量转换成String型变量
357      *@param intVal 要进行转换的整数
358      *@return str 如果intVal不可以转换成String型数据,返回空值表示异常,否则返回转换后的值
359      */
360     public static String int2Str(int intVal) {
361         String str;
362 
363         try {
364             str = String.valueOf(intVal);
365         } catch (Exception e) {
366             str = "";
367         }
368 
369         return str;
370     }
371 
372     /**
373      *long型变量转换成String型变量
374      *@param longVal 要进行转换的整数
375      *@return str 如果longVal不可以转换成String型数据,返回空值表示异常,否则返回转换后的值
376      */
377 
378     public static String long2Str(long longVal) {
379         String str;
380 
381         try {
382             str = String.valueOf(longVal);
383         } catch (Exception e) {
384             str = "";
385         }
386 
387         return str;
388     }
389 
390     /**
391      *null 处理
392      *@param str 要进行转换的字符串
393      *@return 如果str为null值,返回空串"",否则返回str
394      */
395     public static String null2Blank(String str) {
396         if (str == null)
397             return "";
398         else
399             return str;
400     }
401 
402     /**
403      *null 处理
404      *@param d 要进行转换的日期对像
405      *@return 如果d为null值,返回空串"",否则返回d.toString()
406      */
407 
408     public static String null2Blank(Date d) {
409         if (d == null)
410             return "";
411         else
412             return d.toString();
413     }
414 
415     /**
416      *null 处理
417      *@param str 要进行转换的字符串
418      *@return 如果str为null值,返回空串整数0,否则返回相应的整数
419      */
420     public static int null2Zero(String str) {
421         int intTmp;
422         intTmp = str2Int(str);
423         if (intTmp == -1)
424             return 0;
425         else
426             return intTmp;
427     }
428     /**
429      * 把null转换为字符串"0"
430      * @param str
431      * @return
432      */
433     public static String null2SZero(String str) {
434         str = CTool.null2Blank(str);
435         if (str.equals(""))
436             return "0";
437         else
438             return str;
439     }
440 
441     /**
442      * sql语句 处理
443      * @param sql 要进行处理的sql语句
444      * @param dbtype 数据库类型
445      * @return 处理后的sql语句
446      */
447     public static String sql4DB(String sql, String dbtype) {
448         if (!dbtype.equalsIgnoreCase("oracle")) {
449             sql = CTool.toISO(sql);
450         }
451         return sql;
452     }
453 
454     /**
455      * 对字符串进行md5加密
456      * @param s 要加密的字符串
457      * @return md5加密后的字符串
458      */
459     public final static String MD5(String s) {
460         char hexDigits[] = {
461                            ‘0‘, ‘1‘, ‘2‘, ‘3‘, ‘4‘, ‘5‘, ‘6‘, ‘7‘, ‘8‘, ‘9‘,
462                            ‘a‘, ‘b‘, ‘c‘, ‘d‘,
463                            ‘e‘, ‘f‘};
464         try {
465             byte[] strTemp = s.getBytes();
466             MessageDigest mdTemp = MessageDigest.getInstance("MD5");
467             mdTemp.update(strTemp);
468             byte[] md = mdTemp.digest();
469             int j = md.length;
470             char str[] = new char[j * 2];
471             int k = 0;
472             for (int i = 0; i < j; i++) {
473                 byte byte0 = md[i];
474                 str[k++] = hexDigits[byte0 >>> 4 & 0xf];
475                 str[k++] = hexDigits[byte0 & 0xf];
476             }
477             return new String(str);
478         } catch (Exception e) {
479             return null;
480         }
481     }
482     /**
483      * 字符串从GBK编码转换为Unicode编码
484      * @param text
485      * @return
486      */
487     public static String StringToUnicode(String text) {
488         String result = "";
489         int input;
490         StringReader isr;
491         try {
492             isr = new StringReader(new String(text.getBytes(), "GBK"));
493         } catch (UnsupportedEncodingException e) {
494             return "-1";
495         }
496         try {
497             while ((input = isr.read()) != -1) {
498                 result = result + "&#x" + Integer.toHexString(input) + ";";
499 
500             }
501         } catch (IOException e) {
502             return "-2";
503         }
504         isr.close();
505         return result;
506 
507     }
508     /**
509      * 
510      * @param inStr
511      * @return
512      */
513     public static String gb2utf(String inStr) {
514         char temChr;
515         int ascInt;
516         int i;
517         String result = new String("");
518         if (inStr == null) {
519             inStr = "";
520         }
521         for (i = 0; i < inStr.length(); i++) {
522             temChr = inStr.charAt(i);
523             ascInt = temChr + 0;
524             //System.out.println("1=="+ascInt);
525             //System.out.println("1=="+Integer.toBinaryString(ascInt));
526             if( Integer.toHexString(ascInt).length() > 2 ) {
527                 result = result + "&#x" + Integer.toHexString(ascInt) + ";";
528             }
529             else
530             {
531                 result = result + temChr;
532             }
533 
534         }
535         return result;
536     }
537     /**
538      * This method will encode the String to unicode.
539      *
540      * @param gbString
541      * @return
542      */
543 
544     //代码:--------------------------------------------------------------------------------
545     public static String gbEncoding(final String gbString) {
546         char[] utfBytes = gbString.toCharArray();
547         String unicodeBytes = "";
548         for (int byteIndex = 0; byteIndex < utfBytes.length; byteIndex++) {
549             String hexB = Integer.toHexString(utfBytes[byteIndex]);
550             if (hexB.length() <= 2) {
551                 hexB = "00" + hexB;
552             }
553             unicodeBytes = unicodeBytes + "\\u" + hexB;
554         }
555         System.out.println("unicodeBytes is: " + unicodeBytes);
556         return unicodeBytes;
557     }
558 
559     /**
560      * This method will decode the String to a recognized String
561      * in ui.
562      * @param dataStr
563      * @return
564      */
565     public static StringBuffer decodeUnicode(final String dataStr) {
566         int start = 0;
567         int end = 0;
568         final StringBuffer buffer = new StringBuffer();
569         while (start > -1) {
570             end = dataStr.indexOf("\\u", start + 2);
571             String charStr = "";
572             if (end == -1) {
573                 charStr = dataStr.substring(start + 2, dataStr.length());
574             } else {
575                 charStr = dataStr.substring(start + 2, end);
576             }
577             char letter = (char) Integer.parseInt(charStr, 16); // 16进制parse整形字符串。
578             buffer.append(new Character(letter).toString());
579             start = end;
580         }
581         return buffer;
582     }
583 
584 }

 

java综合工具类

标签:style   blog   io   color   ar   os   java   sp   for   

原文地址:http://www.cnblogs.com/leorain/p/4093646.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!