package com.gzcivil.utils;

 import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern; /**
* 字符串工具
*
* @author LiJinlun
* @time 2015-12-5
*/
public class StringUtils { private static StringUtils instance; private StringUtils() {
super();
} public static String getDateTimeToString(Calendar cal, String format) {
return getDateTimeToString(cal.getTimeInMillis(), format);
} public static String getDateTimeToString(long longTime, String format) {
SimpleDateFormat sdf = new SimpleDateFormat(format, Locale.getDefault());
Date date = new Date(longTime);
return sdf.format(date);
} public static synchronized StringUtils getInstance() {
if (instance == null)
instance = new StringUtils();
return instance;
} /** 将一个字符串从第一位开始截取到有数字出现的地方 */
public static String clearNumberString(String str) {
int minIndex = Integer.MAX_VALUE;
int[] index = new int[10];
for (int i = 0; i < 10; i++) {
index[i] = str.indexOf(String.valueOf(i));
if (index[i] != -1 && index[i] < minIndex) {
minIndex = index[i];
}
}
if (minIndex < Integer.MAX_VALUE) {
str = str.substring(0, minIndex);
}
return str;
} /**
* 判断字符串是否为空
*/
public static boolean isEmpty(String str) {
return null == str || str.trim().equals("");
} /**
* 描述:手机号格式验证.
*
* @param str
* 指定的手机号码字符串
* @return 是否为手机号码格式:是为true,否则false
*/
public static Boolean isMobilePhone(String str) {
Boolean isMobileNo = false;
try {
Pattern p = Pattern.compile("^((13[0-9])|(14[0-9])|(15[0-9])|(16[0-9])|(17[0-9])|(18[0-9])|(19[0-9]))\\d{8}$");
Matcher m = p.matcher(str);
isMobileNo = m.matches();
} catch (Exception e) {
e.printStackTrace();
}
return isMobileNo;
} /**
* 获取字串字节长度
*
* @param str
* @return
*/
public static int getLength(String str) {
return str.replaceAll("[^\\x00-\\xff]", "**").trim().length();
} /** 返回double数据d小数点后面2位有效数字 */
public static double getDouble(double d) {
return new BigDecimal(d).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
} /** 从double型返回String型,精确到小数点后2位 */
public static String getStringByDouble(double d) {
String str = String.valueOf(new BigDecimal(d).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
try {
int index = str.indexOf('.');
if (index != -1) {
String tmpStr = str.substring(index + 1);
if ("0".equals(tmpStr)) {
str = str.substring(0, index);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return str;
} public static String getCorrectDistance(int distance) {
String result = "";
if (distance < 20) {
result = "附近";
} else if (distance < 1000) {
result = distance + "m";
} else {
result = String.format("%.1f", distance / 1000f) + "km";
}
return result;
} /**
* 将秒数转换成文字描述
*
* @param tm单位秒
*/
public static String secondsToString(int tm) {
if (tm <= 0)
return "00:00:00";
long hour = tm / 3600;
tm = tm % 3600;
long min = tm / 60;
tm = tm % 60; String result = "";
if (hour < 10) {
result = "0" + hour + ":";
} else {
result = String.valueOf(hour) + ":";
} if (min < 10) {
result += "0" + min + ":";
} else {
result += min + ":";
} if (tm < 10) {
result += "0" + tm;
} else {
result += String.valueOf(tm);
}
return result;
} /**
* 检测是否JSON字串
*
* @param source
* @return
*/
public static boolean isJson(String source) {
String tmp = null == source ? "" : source.trim();
if ("".equals(tmp) || tmp.length() < 1)
return false;
else if (tmp.startsWith("{") && tmp.endsWith("}"))
return true;
else if (tmp.startsWith("[") && tmp.endsWith("]"))
return true;
else
return false;
} public static String str2int(String source) {
String result = "";
LogUtils.i("ls", "result" + result);
for (int i = 0; i < source.length(); i++) {
if (source.charAt(i) >= '0' && source.charAt(i) <= '9')
result += source.charAt(i); }
return result;
} /**
* MD5编码
*
* @param source
* @return
*/
public static String md5(byte[] source) {
char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
try {
java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5");
md.update(source);
byte tmp[] = md.digest();
char str[] = new char[16 * 2];
for (int i = 0, k = 0; i < 16; i++) {
byte byte0 = tmp[i];
str[k++] = hexDigits[byte0 >>> 4 & 0xf];
str[k++] = hexDigits[byte0 & 0xf];
}
return new String(str);
} catch (Exception e) {
LogUtils.e("md5(): error=" + e.getMessage(), "StringTool");
return "";
}
} /**
* base64编码,将字节数组编码为字符串
*
* @param source
* @return String
*/
public static String base64_encode(byte[] source) {
char[] base64EncodeChars = new char[] { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/' };
try {
StringBuffer sb = new StringBuffer();
int len = source.length;
int i = 0;
int b1, b2, b3;
while (i < len) {
b1 = source[i++] & 0xff;
if (i == len) {
sb.append(base64EncodeChars[b1 >>> 2]);
sb.append(base64EncodeChars[(b1 & 0x3) << 4]);
sb.append("==");
break;
}
b2 = source[i++] & 0xff;
if (i == len) {
sb.append(base64EncodeChars[b1 >>> 2]);
sb.append(base64EncodeChars[((b1 & 0x03) << 4) | ((b2 & 0xf0) >>> 4)]);
sb.append(base64EncodeChars[(b2 & 0x0f) << 2]);
sb.append("=");
break;
}
b3 = source[i++] & 0xff;
sb.append(base64EncodeChars[b1 >>> 2]);
sb.append(base64EncodeChars[((b1 & 0x03) << 4) | ((b2 & 0xf0) >>> 4)]);
sb.append(base64EncodeChars[((b2 & 0x0f) << 2) | ((b3 & 0xc0) >>> 6)]);
sb.append(base64EncodeChars[b3 & 0x3f]);
}
return sb.toString();
} catch (Exception e) {
LogUtils.e("base64_encode(): error=" + e.getMessage(), "StringTool");
return "";
}
} /**
* base64编码,解码为字节数组
*
* @param source
* @return byte[]
*/
public static byte[] base64_decode(String source) {
byte[] base64DecodeChars = new byte[] { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1, -1, 0, 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, -1, -1, -1, -1, -1, -1, 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, -1, -1, -1, -1, -1 };
try {
byte[] data = source.getBytes();
int len = data.length;
ByteArrayOutputStream buf = new ByteArrayOutputStream(len);
int i = 0;
int b1, b2, b3, b4;
while (i < len) {
/* b1 */
do {
b1 = base64DecodeChars[data[i++]];
} while (i < len && b1 == -1);
if (b1 == -1)
break; /* b2 */
do {
b2 = base64DecodeChars[data[i++]];
} while (i < len && b2 == -1);
if (b2 == -1)
break;
buf.write((int) ((b1 << 2) | ((b2 & 0x30) >>> 4))); /* b3 */
do {
b3 = data[i++];
if (b3 == 61)
return buf.toByteArray();
b3 = base64DecodeChars[b3];
} while (i < len && b3 == -1);
if (b3 == -1)
break;
buf.write((int) (((b2 & 0x0f) << 4) | ((b3 & 0x3c) >>> 2))); /* b4 */
do {
b4 = data[i++];
if (b4 == 61)
return buf.toByteArray();
b4 = base64DecodeChars[b4];
} while (i < len && b4 == -1);
if (b4 == -1)
break;
buf.write((int) (((b3 & 0x03) << 6) | b4));
}
return buf.toByteArray();
} catch (Exception e) {
LogUtils.i("ls", "base64_decode(): error=" + e.getMessage());
return "".getBytes();
}
} public static String join(String separator, Object[] o) {
return implode(separator, Arrays.asList(o));
} protected static <T> String implode(String separator, Iterable<T> elements) {
StringBuilder out = new StringBuilder();
boolean first = true;
for (Object s : elements) {
if (s == null)
continue;
else if (first)
first = false;
else
out.append(separator);
out.append(s);
}
return out.toString();
} public static String[] explode(String glue, String str) {
String[] outData;
try {
StringTokenizer st = new StringTokenizer(str, glue);
outData = new String[st.countTokens()];
for (int i = 0; st.hasMoreTokens();) {
outData[i++] = st.nextToken();
}
} catch (Exception e) {
outData = new String[] { str };
e.printStackTrace();
}
return outData;
} /**
* 得到字符串双字节长度
*
* @param str
* @return
*/
public static int getDoubleByteLength(String str) {
return str.replaceAll("[^\\x00-\\xff]", "xx").trim().length();
} /**
* 将流转换成字符串
*
* @param is
* @return
*/
public static String getStringByStream(InputStream is) {
StringBuffer sb = new StringBuffer();
try {
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line = null;
while ((line = br.readLine()) != null) {
sb.append(line);
}
} catch (Exception e) {
e.printStackTrace();
}
return sb.toString();
} /**
* 将流转换成字符串
*
* @param is
* @param chatset
* 字符编码
* @return
*/
public static String getStringByStream(InputStream is, String chatset) {
StringBuffer sb = new StringBuffer();
try {
byte[] bytes = new byte[1024];
int len = 0;
while ((len = is.read(bytes)) != -1) {
sb.append(new String(bytes, 0, len, chatset));
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return sb.toString();
} }

android开发字符串工具类(一)的更多相关文章

  1. Android开发常用工具类

    来源于http://www.open-open.com/lib/view/open1416535785398.html 主要介绍总结的Android开发中常用的工具类,大部分同样适用于Java. 目前 ...

  2. 最全Android开发常用工具类

    主要介绍总结的Android开发中常用的工具类,大部分同样适用于Java. 目前包括  HttpUtils.DownloadManagerPro.Safe.ijiami.ShellUtils.Pack ...

  3. android 开发 常用工具类

    转载请标明出处:http://blog.csdn.net/lmj623565791/article/details/38965311,本文出自[张鸿洋的博客] 打开大家手上的项目,基本都会有一大批的辅 ...

  4. android开发Tost工具类管理(一)

    Tost工具类管理: package com.gzcivil.utils; import android.content.Context; import android.widget.Toast; / ...

  5. android 开发 在一个工具类(或者适配器class)里启动activity

    实现思路: 1.需要给工具类里传入context: 2.使用上下文mContext.startActivity启动activity 例子1: public class SafePlaceRecycle ...

  6. Android开发 Html工具类详解

    前言 在一些需求富文本显示或者编辑的开发情况下,数据都是用html的格式来保存文本信息的.而google是有提供解析html的工具类那就是Html.有了Html可以让TextView也支持富文本(其实 ...

  7. 网络请求以及网络请求下载图片的工具类 android开发java工具类

    package cc.jiusan.www.utils; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; ...

  8. Android 开发小工具之:Tools 属性 (转)

    Android 开发小工具之:Tools 属性 http://blog.chengyunfeng.com/?p=755#ixzz4apLZhfmi 今天来介绍一些 Android 开发过程中比较有用但 ...

  9. Android 开发常用工具合集

    在 Android 开发中经常使用到的小功能,用于记录开发的那些事^_^ 1. 获取 release 和 debug 版本的 SHA1 public static String getSHA1(Con ...

随机推荐

  1. apache启动问题: Could not reliably determine the server's fully qualified domain name

    [root@rusky]# service httpd startStarting httpd: httpd: apr_sockaddr_info_get() failed for ruskyhttp ...

  2. MySQL ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: NO

    MySQL安装完server端和客户端后,登录Mysql时报错:[root@rhel204 MySQL 5.6.23-RMP]# mysqlERROR 2002 (HY000): Can't conn ...

  3. Oracle SQL函数之聚组函数

    AVG([distinct|all]x) [功能]统计数据表选中行x列的平均值. [参数]all表示对所有的值求平均值,distinct只对不同的值求平均值,默认为all 如果有参数distinct或 ...

  4. idea maven 无法加载已经安装的模块

    新建了一下maven项目,下面新建了一个模块,某一个模块clean install之后,别的模块虽然使用dependency标签引入了,但是仍然无法使用, 这个时候,应该重新建立一个项目,将原有项目的 ...

  5. 给远程桌面发送“Ctrl+Alt+Delete”组合键

    首先: 在运行里,输入osk, 打开软键盘 然后,这时先按下本地键盘的Ctrl和Alt键,再点远程"软键盘"的"Del"键,成功发送"Ctrl+Alt ...

  6. 动态分配内存补充 realloc

    当再次在原来申请的内存基础上再加内存的时候用realloc,如果第一次分配的内存后面存储地方够用,则连着原来的申请,如果不够用,就重新找到一块够用的地方,然后把原来的复制过去 int main(int ...

  7. WindowsForm 打印

    打印: 打印对话框:printdialog 页面设置:pagesetupdialog 这两个对话框都需要通过设置printdocument来指定打印对象 printdocument:打印对象,必须要有 ...

  8. (重要) html概念之 input:name与id详解

    实例: 带有两个文本字段和一个提交按钮的 HTML 表单: <form action="form_action.asp" method="get"> ...

  9. C++程序设计实践指导1.7超长数列中n个数排序改写要求实现

    改写要求1:将以上程序改写为适合超长整数 改写要求2:将以上程序改写为适合超长数列 改写要求3:将数列中指定位置m开始的n个结点重新按降序排序 改写要求4:输出指定位置m开始的n个结点的超长整数 #i ...

  10. jquery中 append 和appendto的区别

    1. append(content)方法 方法作用:向每个匹配的元素内部追加内容. 参数介绍:content (<Content>): 要追加到目标中的内容. 用法示例: HTML代码为& ...