package com.zhouyou.http.demo.utils; import android.content.Context; import android.text.TextUtils; import org.json.JSONObject; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.net.URLEncoder; import java.text.DecimalFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.Random; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.zip.GZIPInputStream; import java.util.zip.GZIPOutputStream; /** * <b>类名称:</b> StringUtils <br/> * <b>类描述:</b> 字符串工具类<br/> * <b>创建人:</b> 林肯 <br/> * <b>修改人:</b> 编辑人 <br/> * <b>修改时间:</b> 2015年07月29日 下午2:18 <br/> * <b>修改备注:</b> <br/> * * @version 1.0.0 <br/> */ public class StringUtils { private StringUtils() { /* cannot be instantiated */ throw new UnsupportedOperationException("cannot be instantiated"); } /** * 判断字符串是否为空或空字符 * * @param strSource 源字符串 * @return true表示为空,false表示不为空 */ public static boolean isNull(final String strSource) { return strSource == null || "".equals(strSource.trim()); } /** * is null or its length is 0 or it is made by space * <p> * <pre> * isBlank(null) = true; * isBlank("") = true; * isBlank(" ") = true; * isBlank("a") = false; * isBlank("a ") = false; * isBlank(" a") = false; * isBlank("a b") = 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); } /** * 获取字符串长度的安全方法 * get length of CharSequence * <p> * <pre> * length(null) = 0; * length(\"\") = 0; * length(\"abc\") = 3; * </pre> * * @param str * @return if str is null or empty, return 0, else return {@link CharSequence#length()}. */ public static int size(CharSequence str) { return str == null ? 0 : str.length(); } /** * null Object to empty string * <p> * <pre> * nullStrToEmpty(null) = ""; * nullStrToEmpty("") = ""; * nullStrToEmpty("aa") = "aa"; * </pre> * * @param str * @return */ public static String nullStrToEmpty(Object str) { return (str == null ? "" : (str instanceof String ? (String) str : str.toString())); } /** * 转换首字母为大写 * capitalize first letter * <p> * <pre> * capitalizeFirstLetter(null) = null; * capitalizeFirstLetter("") = ""; * capitalizeFirstLetter("2ab") = "2ab" * capitalizeFirstLetter("a") = "A" * capitalizeFirstLetter("ab") = "Ab" * capitalizeFirstLetter("Abc") = "Abc" * </pre> * * @param str * @return */ public static String capitalizeFirstLetter(String str) { if (TextUtils.isEmpty(str)) { return str; } char c = str.charAt(0); return (!Character.isLetter(c) || Character.isUpperCase(c)) ? str : String.valueOf(Character.toUpperCase(c)) + str.substring(1); } /** * 是否是Utf-8字符串 * encoded in utf-8 * <p> * <pre> * utf8Encode(null) = null * utf8Encode("") = ""; * utf8Encode("aa") = "aa"; * utf8Encode("啊啊啊啊") = "%E5%95%8A%E5%95%8A%E5%95%8A%E5%95%8A"; * </pre> * * @param str * @return * @throws UnsupportedEncodingException if an error occurs */ public static String utf8Encode(String str) { if (!TextUtils.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; } /** * 使用utf-8转码 * encoded in utf-8, if exception, return defultReturn * * @param str * @param defultReturn * @return */ public static String utf8Encode(String str, String defultReturn) { if (!TextUtils.isEmpty(str) && str.getBytes().length != str.length()) { try { return URLEncoder.encode(str, "UTF-8"); } catch (UnsupportedEncodingException e) { return defultReturn; } } return str; } /** * 获取<a></a>标签内的内容 * get innerHtml from href * <p> * <pre> * getHrefInnerHtml(null) = "" * getHrefInnerHtml("") = "" * getHrefInnerHtml("mp3") = "mp3"; * getHrefInnerHtml("<a innerHtml</a>") = "<a innerHtml</a>"; * getHrefInnerHtml("<a>innerHtml</a>") = "innerHtml"; * getHrefInnerHtml("<a<a>innerHtml</a>") = "innerHtml"; * getHrefInnerHtml("<a href="baidu.com">innerHtml</a>") = "innerHtml"; * getHrefInnerHtml("<a href="baidu.com" title="baidu">innerHtml</a>") = "innerHtml"; * getHrefInnerHtml(" <a>innerHtml</a> ") = "innerHtml"; * getHrefInnerHtml("<a>innerHtml</a></a>") = "innerHtml"; * getHrefInnerHtml("jack<a>innerHtml</a></a>") = "innerHtml"; * getHrefInnerHtml("<a>innerHtml1</a><a>innerHtml2</a>") = "innerHtml2"; * </pre> * * @param href * @return <ul> * <li>if href is null, return ""</li> * <li>if not match regx, return source</li> * <li>return the last string that match regx</li> * </ul> */ public static String getHrefInnerHtml(String href) { if (TextUtils.isEmpty(href)) { return ""; } String hrefReg = ".*<[\\s]*a[\\s]*.*>(.+?)<[\\s]*/a[\\s]*>.*"; Pattern hrefPattern = Pattern.compile(hrefReg, Pattern.CASE_INSENSITIVE); Matcher hrefMatcher = hrefPattern.matcher(href); if (hrefMatcher.matches()) { return hrefMatcher.group(1); } return href; } /** * Html文本格式转码 * process special char in html * <p> * <pre> * htmlEscapeCharsToString(null) = null; * htmlEscapeCharsToString("") = ""; * htmlEscapeCharsToString("mp3") = "mp3"; * htmlEscapeCharsToString("mp3<") = "mp3<"; * htmlEscapeCharsToString("mp3>") = "mp3\>"; * htmlEscapeCharsToString("mp3&mp4") = "mp3&mp4"; * htmlEscapeCharsToString("mp3"mp4") = "mp3\"mp4"; * htmlEscapeCharsToString("mp3<>&"mp4") = "mp3\<\>&\"mp4"; * </pre> * * @param source * @return */ public static String htmlEscapeCharsToString(String source) { return TextUtils.isEmpty(source) ? source : source.replaceAll("<", "<").replaceAll(">", ">") .replaceAll("&", "&").replaceAll(""", "\""); } /** * 全角字符 转为为半角字符 * transform full width char to half width char * <p> * <pre> * fullWidthToHalfWidth(null) = null; * fullWidthToHalfWidth("") = ""; * fullWidthToHalfWidth(new String(new char[] {12288})) = " "; * fullWidthToHalfWidth("!"#$%&) = "!\"#$%&"; * </pre> * * @param s * @return */ public static String fullWidthToHalfWidth(String s) { if (TextUtils.isEmpty(s)) { return s; } char[] source = s.toCharArray(); for (int i = 0; i < source.length; i++) { if (source[i] == 12288) { source[i] = ' '; // } else if (source[i] == 12290) { // source[i] = '.'; } else if (source[i] >= 65281 && source[i] <= 65374) { source[i] = (char) (source[i] - 65248); } else { source[i] = source[i]; } } return new String(source); } /** * 将半角字符转换为全角字符 * transform half width char to full width char * <p> * <pre> * halfWidthToFullWidth(null) = null; * halfWidthToFullWidth("") = ""; * halfWidthToFullWidth(" ") = new String(new char[] {12288}); * halfWidthToFullWidth("!\"#$%&) = "!"#$%&"; * </pre> * * @param s * @return */ public static String halfWidthToFullWidth(String s) { if (TextUtils.isEmpty(s)) { return s; } char[] source = s.toCharArray(); for (int i = 0; i < source.length; i++) { if (source[i] == ' ') { source[i] = (char) 12288; // } else if (source[i] == '.') { // source[i] = (char)12290; } else if (source[i] >= 33 && source[i] <= 126) { source[i] = (char) (source[i] + 65248); } else { source[i] = source[i]; } } return new String(source); } private static final String DEFAULT_DATE_PATTERN = "yyyy-MM-dd"; private static final String DEFAULT_DATETIME_PATTERN = "yyyy-MM-dd HH:mm:ss"; private final static ThreadLocal<SimpleDateFormat> dateFormater = new ThreadLocal<SimpleDateFormat>() { @Override protected SimpleDateFormat initialValue() { return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); } }; private final static ThreadLocal<SimpleDateFormat> dateFormater2 = new ThreadLocal<SimpleDateFormat>() { @Override protected SimpleDateFormat initialValue() { return new SimpleDateFormat("yyyy-MM-dd"); } }; /** * 判断字符串是否为空 * * @param str null、“ ”、“null”都返回true * @return boolean */ public static boolean isNullString(String str) { return (null == str || isBlank(str.trim()) || "null".equals(str.trim() .toLowerCase())); } public static boolean isEmpty(CharSequence cs) { return cs == null || cs.length() == 0; } public static boolean isBlank(CharSequence cs) { int strLen; if (cs == null || (strLen = cs.length()) == 0) { return true; } for (int i = 0; i < strLen; i++) { if (Character.isWhitespace(cs.charAt(i)) == false) { return false; } } return true; } /** * 格式化字符串 如果为空,返回“” * * @param str * @return String */ public static String formatString(String str) { if (isNullString(str)) { return ""; } else { return str; } } /** * 获得文件名称 * * @param path * @return String */ public static String getFileName(String path) { if (isNullString(path)) return null; int bingindex = path.lastIndexOf("/"); return path.substring(bingindex + 1, path.length()); } /** * 获得文件名称前缀 * * @param path * @return String */ public static String getFileNamePrefix(String path) { if (isNullString(path)) return null; int bingindex = path.lastIndexOf("/"); int endindex = path.lastIndexOf("."); return path.substring(bingindex + 1, endindex); } private static Pattern numericPattern = Pattern.compile("^[0-9\\-]+$"); /** * 判断字符串是否是数字 * * @param src * @return boolean */ public static boolean isNumeric(String src) { boolean return_value = false; if (src != null && src.length() > 0) { Matcher m = numericPattern.matcher(src); if (m.find()) { return_value = true; } } return return_value; } /** * 自动命名文件,命名文件格式如:IP地址+时间戳+三位随机数 .doc * * @param ip ip地址 * @param fileName 文件名 * @return String */ public static String getIPTimeRandName(String ip, String fileName) { StringBuilder buf = new StringBuilder(); if (ip != null) { String str[] = ip.split("\\."); for (String aStr : str) { buf.append(addZero(aStr, 3)); } }// 加上IP地址 buf.append(getTimeStamp());// 加上日期 Random random = new Random(); for (int i = 0; i < 3; i++) { buf.append(random.nextInt(10));// 取三个随机数追加到StringBuffer } buf.append(".").append(getFileExt(fileName));// 加上扩展名 return buf.toString(); } /** * 自动命名文件,命名文件格式如:时间戳+三位随机数 .doc * * @param fileName * @return String */ public static String getTmeRandName(String fileName) { return getIPTimeRandName(null, fileName); } public static String addZero(String str, int len) { StringBuilder s = new StringBuilder(); s.append(str); while (s.length() < len) { s.insert(0, "0"); } return s.toString(); } /** * 获得时间戳 也可以用 :commons-lang.rar 下的:DateFormatUtils类 更为简单 * * @return String */ public static String getTimeStamp() { SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS"); return sdf.format(new Date()); } /** * 获得文件扩展名 * * @param filename * @return String */ public static String getFileExt(String filename) { int i = filename.lastIndexOf(".");// 返回最后一个点的位置 String extension = filename.substring(i + 1);// 取出扩展名 return extension; } /** * 将url进行utf-8编码 * * @param url * @return String */ public static String encodeURL(String url) { try { return URLEncoder.encode(url, "utf-8"); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } } /** * 将url进行utf-8解码 * * @param url * @return String */ public static String decodeURL(String url) { try { return URLDecoder.decode(url, "utf-8"); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } } /** * 格式化日期字符串 也可以用 :commons-lang.rar 下的:DateFormatUtils类 更为简单 * * @param date * @param pattern * @return String */ public static String formatDate(Date date, String pattern) { SimpleDateFormat format = new SimpleDateFormat(pattern); return format.format(date); } /** * 格式化日期字符串 也可以用 :commons-lang.rar 下的:DateFormatUtils类 更为简单 */ public static String formatDate(Date date) { return formatDate(date, DEFAULT_DATE_PATTERN); } /** * 获取当前时间 也可以用 :commons-lang.rar 下的:DateFormatUtils类 更为简单 * * @return String */ public static String getDate() { return formatDate(new Date(), DEFAULT_DATE_PATTERN); } /** * 获取当前时间 * * @return String */ public static String getDateTime() { return formatDate(new Date(), DEFAULT_DATETIME_PATTERN); } /** * 格式化日期时间字符串 */ public static String formatDateTime(Date date) { return formatDate(date, DEFAULT_DATETIME_PATTERN); } /** * 格式化json格式日期 * * @param date * @return String */ @SuppressWarnings("deprecation") public static String formatJsonDateTime(JSONObject date) { Date result = null; try { result = new Date(date.getInt("year"), date.getInt("month"), date.getInt("date"), date.getInt("hours"), date.getInt("minutes"), date.getInt("seconds")); } catch (Exception e) { e.printStackTrace(); } return result == null ? "" : formatDateTime(result); } /** * 将字符串集合 变为以 separator 分割的字符串 * * @param array 字符串集合 * @param separator 分隔符 * @return String */ public static String join(final ArrayList<String> array, String separator) { StringBuilder result = new StringBuilder(); if (array != null && array.size() > 0) { for (String str : array) { result.append(str); result.append(separator); } result.delete(result.length() - 1, result.length()); } return result.toString(); } /** * 压缩字符串 * * @param str * @return String * @throws IOException */ public static String compress(String str) throws IOException { if (str == null || str.length() == 0) { return str; } ByteArrayOutputStream out = new ByteArrayOutputStream(); GZIPOutputStream gzip = new GZIPOutputStream(out); gzip.write(str.getBytes()); gzip.close(); return out.toString("ISO-8859-1"); } /** * 解压缩字符串 * * @param str * @return String * @throws IOException */ public static String uncompress(String str) throws IOException { if (str == null || str.length() == 0) { return str; } ByteArrayOutputStream out = new ByteArrayOutputStream(); ByteArrayInputStream in = new ByteArrayInputStream( str.getBytes("ISO-8859-1")); GZIPInputStream gunzip = new GZIPInputStream(in); byte[] buffer = new byte[256]; int n; while ((n = gunzip.read(buffer)) >= 0) { out.write(buffer, 0, n); } return out.toString("UTF-8"); } /** * <b>description :</b> 去除特殊字符或将所有中文标号替换为英文标号 * * @param input * @return String */ public static String stringFilter(String input) { if (input == null) return null; input = input.replaceAll("【", "[").replaceAll("】", "]") .replaceAll("!", "!").replaceAll(":", ":");// 替换中文标号 String regEx = "[『』]"; // 清除掉特殊字符 Pattern p = Pattern.compile(regEx); Matcher m = p.matcher(input); return m.replaceAll("").trim(); } /** * <b>description :</b> 半角字符转全角字符 * * @param input * @return String */ public static String ToDBC(String input) { if (input == null) return null; char[] c = input.toCharArray(); for (int i = 0; i < c.length; i++) { if (c[i] == 12288) { c[i] = (char) 32; continue; } if (c[i] > 65280 && c[i] < 65375) c[i] = (char) (c[i] - 65248); } return new String(c); } /** * 判断字符串"oldString"是否为null * * @param oldString 需要判断的字符串 * @return String 如果"oldString"为null返回空值"",否则返回"oldString" */ public static String getString(String oldString) { if (oldString == null || "null".equals(oldString)) { return ""; } else { return oldString.trim(); } } /** * 将一实数转换成字符串并返回 * * @param d 实数 * @return String */ public static String getString(double d) { return String.valueOf(d); } /** * 得到文件的后缀名(扩展名) * * @param name * @return String 后缀名 */ public static String getAfterPrefix(String name) throws Exception { return name.substring(name.lastIndexOf(".") + 1, name.length()); } /** * 分割字符串 * * @param values 要分割的内容 * @param limit 分隔符 例:以“,”分割 * @return String[] 返回数组,没有返回null */ public static String[] spilctMoreSelect(String values, String limit) { if (isNullOrEmpty(values)) { return null; } return values.trim().split(limit); } /** * 将字符串数组转化为字符串 * * @param needvalue * @return String 返回字符串,否则返回null */ public static String arr2Str(String[] needvalue) { String str = ""; if (needvalue != null) { int len = needvalue.length; for (int i = 0; i < len; i++) { if (i == len - 1) { str += needvalue[i]; } else { str += needvalue[i] + ","; } } return str; } else { return null; } } public static int arr2int(String[] arr) { if (arr != null && arr.length > 0) { return Integer.parseInt(arr[1]); } return -1; } /** * 判断字符串是否为空或空符串。 * * @param str 要判断的字符串。 * @return String 返回判断的结果。如果指定的字符串为空或空符串,则返回true;否则返回false。 */ public static boolean isNullOrEmpty(String str) { return (str == null) || (str.trim().length() == 0); } /** * 去掉字符串两端的空白字符。因为String类里边的trim()方法不能出现null.trim()的情况,因此这里重新写一个工具方法。 * * @param str 要去掉空白的字符串。 * @return String 返回去掉空白后的字符串。如果字符串为null,则返回null;否则返回str.trim()。 * */ public static String trim(String str) { return str == null ? null : str.trim(); } /** * 更具配置的string.xml 里的id,得到内容 * * @param context * @param id * @return String */ public static String getValueById(Context context, int id) { return context.getResources().getString(id); } /** * 用于文中强制换行的处理 * * @param oldstr * @return String */ public static String replaceStr(String oldstr) { oldstr = oldstr.replaceAll("\n", "<br>");// 替换换行 oldstr = oldstr.replaceAll("\r\n", "<br>");// 替换回车换行 oldstr = oldstr.replaceAll(" ", " " + " ");// 替换空格 return oldstr; } /** * 判断是否是数字 * * @param c * @return boolean */ public static boolean isNum(char c) { return c >= 48 && c <= 57; } /** * 获得题号 例如:2.本文选自哪篇文章? 提取题号中的数字 2 * * @param content * @return int */ public static int getThemeNum(String content) { int tnum = -1; if (isNullOrEmpty(content)) return tnum; int a = content.indexOf("."); if (a > 0) { String num = content.substring(0, a); try { tnum = Integer.parseInt(num); } catch (NumberFormatException e) { e.printStackTrace(); return tnum; } } return tnum; } // 添加自己的字符串操作 public static String dealDigitalFlags(String str) { String result = ""; if (str == null || str.length() < 0) { return null; } else { int len = str.length(); for (int i = 0; i < len; i++) { String tmp = str.substring(i, i + 1); if (tmp.equals("+") || tmp.equals("*") || tmp.equals("=")) { tmp = " " + tmp + " "; } result += tmp; } } return result; } /** * 截取序号 例如:01026---->26 * * @param oldnum * @return String */ public static String detailNum(String oldnum) { if (isNullOrEmpty(oldnum)) return oldnum; int newnum = Integer.parseInt(oldnum); return newnum + "."; } public static String[] getStoreArr(String[] arr) throws Exception { String temp; for (int i = 0; i < arr.length; i++) { for (int j = arr.length - 1; j > i; j--) { int a = Integer.parseInt(arr[i]); int b = Integer.parseInt(arr[j]); if (a > b) { temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } } } return arr; } /** * 给数字字符串排序 如:3,1,2 --->1,2,3 * * @param str * @return String * @throws Exception */ public static String resetStoreNum(String str) { String value = ""; try { if (str == null || str.length() < 1) return value; String[] results = str.split(","); String[] newarr = getStoreArr(results); for (String aNewarr : newarr) { value += aNewarr + ","; } value = value.substring(0, value.length() - 1); } catch (Exception e) { e.printStackTrace(); } return value; } /** * 判断数组中是否包含某个值 * * @param srcValue * @param values * @return boolean */ public static boolean arrIsValue(String srcValue, String[] values) { if (values == null) { return false; } for (String value : values) { if (value.equals(srcValue)) { return true; } } return false; } /** * 获得"."之后的所有内容 * * @param content 原字符串 * @return String */ public static String DeleteOriNumber(String content) { if (content.trim().length() > 1) { int index = content.indexOf("."); String AfterStr = content.substring(index + 1, content.length()); return AfterStr; } else { return content; } } /** * GBK编码 * * @param content * @return String */ public static String convertToGBK(String content) { if (!isEmpty(content)) { try { content = new String(content.getBytes(), "GBK"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } return content; } private static String trimSpaces(String IP) {// 去掉IP字符串前后所有的空格 while (IP.startsWith(" ")) { IP = IP.substring(1, IP.length()).trim(); } while (IP.endsWith(" ")) { IP = IP.substring(0, IP.length() - 1).trim(); } return IP; } /** * 判断是否是一个IP * * @param IP * @return boolean */ public static boolean isIp(String IP) { boolean b = false; IP = trimSpaces(IP); if (IP.matches("\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}")) { String s[] = IP.split("\\."); if (Integer.parseInt(s[0]) < 255) if (Integer.parseInt(s[1]) < 255) if (Integer.parseInt(s[2]) < 255) if (Integer.parseInt(s[3]) < 255) b = true; } return b; } /** * 将字符串转位日期类型 * * @param sdate * @return Date */ public static Date toDate(String sdate) { try { return dateFormater.get().parse(sdate); } catch (ParseException e) { return null; } } /** * 方法: distanceSize * 描述: 计算距离 * * @param distance 距离数 单位千米 * @return String 转换后的距离 */ public static String distanceSize(double distance) { if (distance < 1.0) return (int) (distance * 1000) + "m"; String dd = "0"; try { DecimalFormat fnum = new DecimalFormat("##0.00"); dd = fnum.format(distance); } catch (Exception e) { e.printStackTrace(); } return dd + "km"; } /** * 方法: replaceResult * 描述: 替换结果字符串 * * @param content * @return String 返回类型 */ public static String replaceResult(String content) { if (!isEmpty(content)) content = content.replace("\\", "").replace("\"{", "{").replace("}\"", "}"); return content; } /** * 方法: checkPhone * 描述: 提取电话号码 * * @param content * @return ArrayList<String> 返回类型 */ public static ArrayList<String> checkPhone(String content) { ArrayList<String> list = new ArrayList<String>(); if (isEmpty(content)) return list; Pattern p = Pattern.compile("1([\\d]{10})|((\\+[0-9]{2,4})?\\(?[0-9]+\\)?-?)?[0-9]{7,8}"); Matcher m = p.matcher(content); while (m.find()) { list.add(m.group()); } return list; } /** * <p>描述:保留一位小数</p> * * @param value * @return 设定文件 */ public static String parseStr(String value) { if (isNullString(value)) return "0.0"; DecimalFormat df = new DecimalFormat("######0.0"); double mvalue = Double.parseDouble(value); return df.format(mvalue); } public static String parseStr2(String value) { if (isNullString(value)) return "--"; DecimalFormat df = new DecimalFormat("######0.0"); double mvalue = Double.parseDouble(value); String mStr = df.format(mvalue); if (mStr.equals("0") || mStr.equals("0.0")) { return "--"; } return mStr; } public static String parseStr(double value) { if (value == 0) return "0.0"; DecimalFormat df = new DecimalFormat("######0.0"); return df.format(Double.parseDouble(String.valueOf(value))); } /** * 处理自动换行问题 * * @param input 字符串 * @return 设定文件 */ public static String ToWrap(String input) { char[] c = input.toCharArray(); for (int i = 0; i < c.length; i++) { if (c[i] == 12288) { c[i] = (char) 32; continue; } if (c[i] > 65280 && c[i] < 65375) c[i] = (char) (c[i] - 65248); } return new String(c); } /** * 时间显示转换 * * @param duration 时间区间 0-59 * @param isShowZero 小于10是否显示0 如:09 * @return */ public static String durationShow(int duration, boolean isShowZero) { String showStr; if (isShowZero) { if (duration < 10) { showStr = "0" + String.valueOf(duration); } else { showStr = String.valueOf(duration); } } else { showStr = String.valueOf(duration); } return showStr; } public static long fromTimeString(String s) { if (s.lastIndexOf(".") != -1) { s = s.substring(0, s.lastIndexOf(".")); } String[] split = s.split(":"); if (split.length == 3) { return Long.parseLong(split[0]) * 3600L + Long.parseLong(split[1]) * 60L + Long.parseLong(split[2]); } else if (split.length == 2) { return Long.parseLong(split[0]) * 60L + Long.parseLong(split[0]); } else { throw new IllegalArgumentException("Can\'t parse time string: " + s); } } public static String toTimeString(long seconds) { seconds = seconds / 1000; long hours = seconds / 3600L; long remainder = seconds % 3600L; long minutes = remainder / 60L; long secs = remainder % 60L; if (hours == 0) { return (minutes < 10L ? "0" : "") + minutes + ":" + (secs < 10L ? "0" : "") + secs; } return (hours < 10L ? "0" : "") + hours + ":" + (minutes < 10L ? "0" : "") + minutes + ":" + (secs < 10L ? "0" : "") + secs; } /** * 是否含有表情符 * false 为含有表情符 */ public static boolean checkFace(String checkString) { String reg = "^([a-z]|[A-Z]|[0-9]|[\u0000-\u00FF]|[\u2000-\uFFFF]){1,}$"; Pattern pattern = Pattern.compile(reg); Matcher matcher = pattern.matcher(checkString.replaceAll(" ", "")); return matcher.matches(); } }