功能:十六進制字符串與字節數組互轉、字符轉字節、Blob類型轉字節數組、阿拉伯數字轉中文小寫
1 import java.io.BufferedInputStream; 2 import java.io.IOException; 3 import java.sql.Blob; 4 5 /** 6 * 常用類型轉換方法工具類 7 */ 8 public class ConvertUtil { 9 10 /** 11 * 字節數組轉換為十六進制字符串. 12 * @param src 13 * @return 十六進制字符串 14 */ 15 public static String bytesToHexString(byte[] src){ 16 StringBuilder stringBuilder = new StringBuilder(""); 17 if (src == null || src.length <= 0) { 18 return null; 19 } 20 for (int i = 0; i < src.length; i++) { 21 int v = src[i] & 0xFF; 22 String hv = Integer.toHexString(v); 23 if (hv.length() < 2) { 24 stringBuilder.append(0); 25 } 26 stringBuilder.append(hv); 27 } 28 return stringBuilder.toString(); 29 } 30 31 /** 32 * 十六進制字符串轉換為字節數組 33 * @param hexString 十六進制字符串 34 * @return 35 */ 36 public static byte[] hexStringToBytes(String hexString) { 37 if (hexString == null || hexString.equals("")) { 38 return null; 39 } 40 hexString = hexString.toUpperCase(); 41 int length = hexString.length() / 2; 42 char[] hexChars = hexString.toCharArray(); 43 byte[] d = new byte[length]; 44 for (int i = 0; i < length; i++) { 45 int pos = i * 2; 46 d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1])); 47 } 48 return d; 49 } 50 51 /** 52 * 字符轉換為字節 53 * @param c 字符 54 * @return 55 */ 56 private static byte charToByte(char c) { 57 return (byte) "0123456789ABCDEF".indexOf(c); 58 } 59 60 /** 61 * Blob類型轉換為字節數組 62 * @param blob 63 * @return 64 */ 65 public static byte[] blobToBytes(Blob blob) { 66 BufferedInputStream is = null; 67 try { 68 is = new BufferedInputStream(blob.getBinaryStream()); 69 byte[] bytes = new byte[(int) blob.length()]; 70 int len = bytes.length; 71 int offset = 0; 72 int read = 0; 73 74 while (offset < len && (read = is.read(bytes, offset, len - offset)) >= 0) { 75 offset += read; 76 } 77 return bytes; 78 } catch (Exception e) { 79 return null; 80 } finally { 81 try { 82 is.close(); 83 is = null; 84 } catch (IOException e) { 85 return null; 86 } 87 } 88 } 89 90 /** 91 * 阿拉伯數字轉中文小寫 92 * @param si 阿拉伯數字 93 * @return 中文小寫字符串 94 */ 95 public static String transition(String si){ 96 String []aa={"","十","百","千","萬","十萬","百萬","千萬","億","十億"}; 97 String []bb={"一","二","三","四","五","六","七","八","九"}; 98 char[] ch=si.toCharArray(); 99 int maxindex=ch.length; 100 // 字符的轉換 101 String result = ""; 102 // 兩位數的特殊轉換 103 if(maxindex==2){ 104 for(int i=maxindex-1,j=0;i>=0;i--,j++){ 105 if(ch[j]!=48){ 106 if(j==0&&ch[j]==49){ 107 result += aa[i]; 108 }else{ 109 result += bb[ch[j]-49]+aa[i]; 110 } 111 } 112 } 113 // 其他位數的特殊轉換,使用的是int類型最大的位數為十億 114 }else{ 115 for(int i=maxindex-1,j=0;i>=0;i--,j++){ 116 if(ch[j]!=48){ 117 result += bb[ch[j]-49]+aa[i]; 118 } 119 } 120 } 121 122 return result; 123 } 124 } View Code