1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
package com.moral.andbrickslib.utils;
 
import android.content.Context;
import android.telephony.TelephonyManager;
 
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
 
/**
 * 字符串工具类
 *
 * @author Administrator
 */
public class StringUtils {
    private static final int MAX_PASSWORD_LENGTH = 16;
    private static final int MIN_PASSWORD_LENGTH = 6;
 
    public static final String URL_REG_EXPRESSION = "^(https?://)?([a-zA-Z0-9_-]+\\.[a-zA-Z0-9_-]+)+(/*[A-Za-z0-9/\\-_&:?\\+=//.%]*)*";
 
    /**
     * is null or its length is 0 or it is made by space
     *
     * <pre>
     * isBlank(null) = true;
     * isBlank(&quot;&quot;) = true;
     * isBlank(&quot;  &quot;) = true;
     * isBlank(&quot;a&quot;) = false;
     * isBlank(&quot;a &quot;) = false;
     * isBlank(&quot; a&quot;) = false;
     * isBlank(&quot;a b&quot;) = false;
     * </pre>
     *
     * @param str
     * @return if string is null or its size is 0 or it is made by space, return true, else return false.
     */
    public static boolean isBlank(String str) {
        return (str == null || str.trim().length() == 0);
    }
 
    /**
     * is null or its length is 0
     *
     * <pre>
     * isEmpty(null) = true;
     * isEmpty(&quot;&quot;) = true;
     * isEmpty(&quot;  &quot;) = false;
     * </pre>
     *
     * @param str
     * @return if string is null or its size is 0, return true, else return false.
     */
    public static boolean isEmpty(String str) {
        return (str == null || str.length() == 0) && isBlank(str);
    }
 
 
    /**
     * 隐藏号码
     *
     * @param mobileStr
     * @param subStr
     * @return
     */
    public static String replacePhoneStr(String mobileStr, String subStr) {
        String resultStr = "";
        if (resultStr != null) {
            resultStr = mobileStr.substring(0, 3) + subStr
                    + mobileStr.substring(7, 11);
        }
        return resultStr;
    }
 
    /**
     * 解码UTF-8
     *
     * @param urlString
     * @return
     */
    public static String decodeUTF8(String urlString) {
        return decodeUrl(urlString.replaceAll("%", ""), "utf-8");
    }
 
    public static String decodeUrl(String urlString, String decode) {
        String decodeStr = "";
        if (urlString != null) {
            try {
                decodeStr = URLDecoder.decode(urlString, decode);
            } catch (UnsupportedEncodingException e) {
            }
        }
        return decodeStr;
    }
 
    /**
     * 编码UTF-8
     *
     * @param str
     * @return
     */
    public static String utf8Encode(String str) {
        if (!isEmpty(str) && str.getBytes().length != str.length()) {
            try {
                return URLEncoder.encode(str, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                throw new RuntimeException("UnsupportedEncodingException occurred. ", e);
            }
        }
        return str;
    }
 
    /**
     * 判断密码是否符合要求
     *
     * @param string
     * @return
     */
    public static boolean isValidPassword(String string) {
        boolean isValid = true;
        if (string != null && !"".equals(string)) {
            if (string.length() >= MIN_PASSWORD_LENGTH
                    && string.length() <= MAX_PASSWORD_LENGTH) {
                int length = string.length();
                for (int i = 0; i < length; i++) {
                    int a = string.charAt(i);
                    if (a >= 32 && a <= 126) {
                        // do nothing
                    } else {
                        isValid = false;
                    }
                }
            } else {
                isValid = false;
            }
        } else {
            isValid = false;
        }
        return isValid;
    }
 
    /**
     * 校验邮箱地址是否合法
     *
     * @param address 邮箱地址
     * @return 结果
     */
    public static boolean isEmailAddressLegal(String address) {
        if (address
                .matches("\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*")) {
            return true;
        }
        return false;
    }
 
    /**
     * 描述:手机号格式验证.
     *
     * @param str 指定的手机号码字符串
     * @return 是否为手机号码格,是为true,否则false
     */
    public static Boolean isMobilePhone(String str) {
        Boolean isMobileNo = false;
        try {
            Pattern p = Pattern
                    .compile("^[1][0-9][0-9]{9}$");
            Matcher m = p.matcher(str);
            isMobileNo = m.matches();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return isMobileNo;
    }
 
    /**
     * 判断账号是否是有中文
     *
     * @param account
     * @return 0 success, other error 1 for length error 2 context error 3
     */
    public static byte isValidAccount(String account) {
        byte _bReturnValue = 0;
        String chinese = "[\u0391-\uFFE5]";
        String expr = "^[A-Za-z0-9_]+$";
        do {
            if (account.length() < 2 || account.length() > 18) {
                _bReturnValue = 1;
                break;
            }
            // 验证内容
            String temp = "";
            for (int i = 0; i < account.length(); i++) {
                // 获取每个字符
                temp = account.substring(i, i + 1);
                // 判断是否是中文
                if (temp.matches(chinese))
                    continue;
                // 判断是否是字母 、数字、下划线
                if (temp.matches(expr))
                    continue;
 
                _bReturnValue = 2;
 
                return _bReturnValue;
            }
        } while (false);
 
        return _bReturnValue;
    }
 
    /**
     * 转换文件大小
     *
     * @param fileS
     * @return
     */
    public static String FormetFileSize(long fileS) {// 转换文件大小
        DecimalFormat df = new DecimalFormat("#0.0");
        String fileSizeString = "";
        if (fileS < 1024) {
            fileSizeString = df.format((double) fileS) + "B";
        } else if (fileS < 1048576) {
            fileSizeString = df.format((double) fileS / 1024) + "K";
        } else if (fileS < 1073741824) {
            fileSizeString = df.format((double) fileS / 1048576) + "M";
        } else {
            fileSizeString = df.format((double) fileS / 1073741824) + "G";
        }
        return fileSizeString;
    }
 
    /**
     * 获取文件夹大小
     *
     * @param f
     * @return
     * @throws Exception
     */
    public static long getFileSize(File f) throws Exception// 取得文件夹大小
    {
        long size = 0;
        File flist[] = f.listFiles();
        for (int i = 0; i < flist.length; i++) {
            if (flist[i].isDirectory()) {
                size = size + getFileSize(flist[i]);
            } else {
                size = size + flist[i].length();
            }
        }
        return size;
    }
 
    /**
     * 判断是否是url
     *
     * @param s
     * @return
     */
    public static boolean isUrl(String s) {
        if (s == null) {
            return false;
        }
        return Pattern.matches(URL_REG_EXPRESSION, s);
    }
 
    public static String getIMSI(Context context) {
        try {
            if (context == null) {
                return "";
            }
            TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
            return telephonyManager.getSubscriberId();
        } catch (Exception exception1) {
        }
        return "";
    }
 
    public static String getIMEI(Context context) {
        try {
            if (context == null) {
                return "";
            }
            TelephonyManager telephonyManager = (TelephonyManager) context
                    .getSystemService(Context.TELEPHONY_SERVICE);
            String imei = telephonyManager.getDeviceId();
            if (imei != null && !imei.equals("")) {
                return imei;
            }
        } catch (Exception exception1) {
        }
 
        return "";
    }
 
    /**
     * 获取设备唯一号
     *
     * @param context
     * @return
     */
    public static String getDeviceId(Context context) {
        try {
            String strIMEI = getIMEI(context);
            if (strIMEI == null || strIMEI.equals("")) {
                strIMEI = getIMSI(context);
                if (strIMEI == null || strIMEI.equals("")) {
                    return "";
                }
            }
            String strTemp = strIMEI + strIMEI + strIMEI;
            String strMd5 = MD5.hexdigest(strTemp.getBytes());
            return strMd5;
        } catch (Exception exception1) {
        }
        return "";
    }
 
    /**
     * 富文本显示
     *
     * @param bodyHTML
     * @return
     */
    public static String getHtmlData(String bodyHTML) {
        String head = "<head>"
                + "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, user-scalable=no\"> "
                + "<style>img{max-width: 100%; width:auto; height:auto;}</style>"
                + "</head>";
        return "<html>" + head + "<body>" + bodyHTML + "</body></html>";
    }
 
    /**
     * html转String
     *
     * @param source
     * @return
     */
    public static String htmlEscapeCharsToString(String source) {
        return isEmpty(source) ? source : source.replaceAll("&lt;", "<").replaceAll("&gt;", ">")
                .replaceAll("&amp;", "&").replaceAll("&quot;", "\"");
    }
 
    /**
     * 将两个ASCII字符合成一个字节; 如:"EF"–> 0xEF
     *
     * @param src0 byte
     * @param src1 byte
     * @return byte
     */
    public static byte uniteBytes(byte src0, byte src1) {
        byte _b0 = Byte.decode("0x" + new String(new byte[]{src0})).byteValue();
        _b0 = (byte) (_b0 << 4);
        byte _b1 = Byte.decode("0x" + new String(new byte[]{src1})).byteValue();
        byte ret = (byte) (_b0 ^ _b1);
        return ret;
    }
 
    /**
     * 将指定字符串src,以每两个字符分割转换为16进制形式 如:"2B44EFD9" –> byte[]{0x2B, 0×44, 0xEF,
     * 0xD9}
     *
     * @param src String
     * @return byte[]
     */
    public static byte[] HexString2Bytes(String src) {
        if (null == src || 0 == src.length()) {
            return null;
        }
        byte[] ret = new byte[src.length() / 2];
        byte[] tmp = src.getBytes();
        for (int i = 0; i < (tmp.length / 2); i++) {
            ret[i] = uniteBytes(tmp[i * 2], tmp[i * 2 + 1]);
        }
        return ret;
    }
 
    public static String byteArrayToHexStr(byte[] byteArray) {
        if (byteArray == null) {
            return null;
        }
        char[] hexArray = "0123456789ABCDEF".toCharArray();
        char[] hexChars = new char[byteArray.length * 2];
        for (int j = 0; j < byteArray.length; j++) {
            int v = byteArray[j] & 0xFF;
            hexChars[j * 2] = hexArray[v >>> 4];
            hexChars[j * 2 + 1] = hexArray[v & 0x0F];
        }
        return new String(hexChars);
    }
 
    public static String dumpHex(byte[] src) {
        String num = "0123456789ABCDEF";
        StringBuilder sb = new StringBuilder();
//        sb.append("[ ");
        for (byte aSrc : src) {
            int high = aSrc >> 4 & 0x0f;
            int low = aSrc & 0x0f;
            sb.append(num.charAt(high)).append(num.charAt(low)).append(" ");
        }
//        sb.append(" ]");
        return sb.toString();
    }
 
    public static String str2HexStr(String str) {
 
        char[] chars = "0123456789ABCDEF".toCharArray();
        StringBuilder sb = new StringBuilder("");
        byte[] bs = str.getBytes();
        int bit;
 
        for (int i = 0; i < bs.length; i++) {
            bit = (bs[i] & 0x0f0) >> 4;
            sb.append(chars[bit]);
            bit = bs[i] & 0x0f;
            sb.append(chars[bit]);
            sb.append(' ');
        }
        return sb.toString().trim();
    }
 
    /**
     * 按照字符串长度分段
     *
     * @param msg
     * @param split
     * @return
     */
    public static String[] splitString(String msg, int split) {
        msg = msg.replace(" ", "");
        String[] strings = new String[msg.length() / split];
        int j = 0;
        for (int i = 0; i < msg.length(); i++) {
            if (i % split == 1) {
                strings[j++] = msg.substring(i - (split - 1), i + 1);
            }
        }
        return strings;
    }
 
    /**
     * 指定字符串长度
     *
     * @param strings
     * @param start
     * @param end
     * @return
     */
    public static String subStrings(String[] strings, int start, int end) {
        StringBuffer buffer = new StringBuffer();
        for (int i = start; i <= end; i++) {
            buffer.append(strings[i]);
        }
        return buffer.toString().trim();
    }
}