具体代码如下:
package com.llkj.core.utils;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.provider.Settings;
import android.text.TextUtils;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
* 字符串工具类 豪哥
public class StringUtils2 {
/**
* String转换成int
*
* @param string
* @return
*/
public static int stringToInt(String string) {
int j = 0;
String str = string.substring(0, string.indexOf("."));
int intgeo = Integer.parseInt(str);
return intgeo;
}
public static String twoDecimalPlaces(String str) {
try {
DecimalFormat df = new DecimalFormat("0.00");
return String.valueOf(df.format(Double.parseDouble(str)));
} catch (Exception e) {
return str;
}
}
public static String twoDecimalPlaces(double str) {
try {
DecimalFormat df = new DecimalFormat("0.00");
return String.valueOf(df.format(str));
} catch (Exception e) {
return String.valueOf(str);
}
}
public static String numberFormat(String str) {
try {
DecimalFormat df = new DecimalFormat("0.00");
double v = Double.parseDouble(str);
if (v < 10000) {
return str;
} else {
return String.valueOf(df.format(v / 10000)) + "万";
}
} catch (Exception e) {
return str;
}
}
/**
* 判断字符串是否为空
*
* @param s
* @return 字符串是否为空
*/
public static boolean isEmpty(String s) {
boolean b = true;
if (s != null && !s.trim().equals("")) {
b = false;
}
return b;
}
// 为图片创建不同的名字
public static String createFileName() {
String fileName = "";
// 系统当前时间
Date date = new Date(System.currentTimeMillis());
SimpleDateFormat dateFormat = new SimpleDateFormat("'IMG'_yyyyMMdd_HHmmss");
fileName = dateFormat.format(date) + ".jpg";
return fileName;
}
//在一定范围内生成随机数.
public static int createRandom() {
Random random = new Random();
return random.nextInt();
}
/**
* 判断字符串是否有表情或特殊字符
*/
public static boolean isEmoji(String string) {
Pattern p = Pattern.compile("[\ud83c\udc00-\ud83c\udfff]|[\ud83d\udc00-\ud83d\udfff]|[\u2600-\u27ff]",
Pattern.UNICODE_CASE | Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher(string);
return m.find();
}
/*
* 流量转换
*/
public static String flowTo(Long ms) {
Integer ss = 1024;
Long b = ms;
Long kb = b / ss;
Long m = kb / ss;
Long g = m / ss;
Long t = g / ss;
String flow = "";
if (t > 0) {
flow = t + "T";
} else if (g > 0) {
flow = g + "G";
} else if (m > 0) {
flow = m + "M";
} else if (kb > 0) {
flow = kb + "kb";
}
return flow;
}
/*
* 毫秒转化时分秒毫秒
*/
public static String formatTime(Long ms) {
Integer ss = 1000;
Integer mi = ss * 60;
Integer hh = mi * 60;
Integer dd = hh * 24;
Long day = ms / dd;
Long hour = (ms - day * dd) / hh;
Long minute = (ms - day * dd - hour * hh) / mi;
Long second = (ms - day * dd - hour * hh - minute * mi) / ss;
// Long milliSecond = ms - day * dd - hour * hh - minute * mi - second * ss;
StringBuffer sb = new StringBuffer();
if (day > 0) {
sb.append(day + ":");
}
if (hour > 0) {
sb.append(hour + ":");
}
if (minute > 0) {
sb.append(minute + ":");
}
if (second > 0) {
sb.append(second + "");
}
// if(milliSecond > 0) {
// sb.append(milliSecond+"毫秒");
// }
return sb.toString();
}
/**
* 判断是否是邮箱
*
* @param strEmail
* @return
*/
public static boolean isEmail(String strEmail) {
String strPattern = "^([a-z0-9A-Z_]+[-\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
Pattern p = Pattern.compile(strPattern);
Matcher m = p.matcher(strEmail);
return m.matches();
}
/**
* 判断密码匹配规则
*
* @param pwd
* @return
*/
public static boolean isPwdMatchRule(String pwd) {
if (pwd == null)
return false;
// Pattern pattern = Pattern.compile("[A-Za-z0-9]{6,16}");
Pattern pattern = Pattern.compile("^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,20}$");// 数字字母组合
Matcher matcher = pattern.matcher(pwd);
return matcher.matches();
}
/**
* 网址匹配规则
*
* @param httpUrl
* @return
*/
public static boolean isHttpUrl(String httpUrl) {
if (httpUrl == null)
return false;
// return httpUrl.startsWith("http://")||httpUrl.startsWith("https://");
// Pattern pattern = Pattern.compile("[A-Za-z0-9]{6,16}");
Pattern pattern = Pattern.compile("[a-zA-z]+://[^\\s]*");// 数字字母组合
Matcher matcher = pattern.matcher(httpUrl);
return matcher.matches();
}
/**
* 判读名称匹配规则
*
* @param name
* @return
*/
public static boolean isNameMatchRule(String name) {
if (name == null)
return false;
Pattern pattern = Pattern.compile("[A-Za-z0-9_]{6,16}");
Matcher matcher = pattern.matcher(name);
return matcher.matches();
}
/**
* 判读是否平常字符
*
* @param
* @return
*/
public static boolean isUsualCharacter(String str) {
if (str == null)
return false;
Pattern pattern = Pattern.compile("[A-Za-z0-9_]");
Matcher matcher = pattern.matcher(str);
return matcher.matches();
}
/**
* 判断是否是中文
*
* @param str
* @return
*/
public static boolean isChinese(String str) {
String regEx = "[\\u4e00-\\u9fa5]";
Pattern p = Pattern.compile(regEx);
Matcher m = p.matcher(str);
while (m.find()) {
for (int i = 0, size = m.groupCount(); i <= size; i++) {
return true;
}
}
return false;
}
/**
* 得到中文数字个数
*
* @param str
* @return
*/
public static int getChineseCount(String str) {
int count = 0;
String regEx = "[\\u4e00-\\u9fa5]";
Pattern p = Pattern.compile(regEx);
Matcher m = p.matcher(str);
while (m.find()) {
for (int i = 0, size = m.groupCount(); i <= size; i++) {
count = count + 1;
}
}
return count;
}
/**
* 得到字符串中的中文集合
*
* @param str
* @return
*/
public static ArrayList<String> getChineseList(String str) {
char[] chars = str.toCharArray();
ArrayList<String> strList = new ArrayList<String>();
StringBuffer sb = new StringBuffer();
for (int i = 0; i < chars.length; i++) {
if (i == chars.length - 1 && isChinese(chars[i] + "")) {// 最后是中文的情况
sb.append(chars[i]);
strList.add(sb.toString());
} else {
if (isChinese(chars[i] + "")) {
sb.append(chars[i]);
} else {
if (sb.toString() != null && sb.toString().trim() != "") {
strList.add(sb.toString());
}
sb.setLength(0);
}
}
}
return strList;
}
/**
* 校验银行卡卡号
*/
public static boolean checkBankCard(String bankCard) {
if (bankCard.length() < 15 || bankCard.length() > 19) {
return false;
}
char bit = getBankCardCheckCode(bankCard.substring(0, bankCard.length() - 1));
if (bit == 'N') {
return false;
}
return bankCard.charAt(bankCard.length() - 1) == bit;
}
/**
* 从不含校验位的银行卡卡号采用 Luhm 校验算法获得校验位
*
* @param nonCheckCodeBankCard
* @return
*/
public static char getBankCardCheckCode(String nonCheckCodeBankCard) {
if (nonCheckCodeBankCard == null || nonCheckCodeBankCard.trim().length() == 0
|| !nonCheckCodeBankCard.matches("\\d+")) {
//如果传的不是数据返回N
return 'N';
}
char[] chs = nonCheckCodeBankCard.trim().toCharArray();
int luhmSum = 0;
for (int i = chs.length - 1, j = 0; i >= 0; i--, j++) {
int k = chs[i] - '0';
if (j % 2 == 0) {
k *= 2;
k = k / 10 + k % 10;
}
luhmSum += k;
}
return (luhmSum % 10 == 0) ? '0' : (char) ((10 - luhmSum % 10) + '0');
}
/**
* 隐藏软键盘
*
* @param mEditText 输入框
* @param mContext 上下文
*/
public static void closeKeybord(final EditText mEditText, final Context mContext) {
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
InputMethodManager imm = (InputMethodManager) mContext
.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(mEditText.getWindowToken(), 0);
}
}, 0);
}
/**
* BitmapUtils中包含中文图片不显示的编码处理,
*
* @param path URL 路径
* @param strList 中文的集合
* @return
*/
public static String getNewPath(String path, ArrayList<String> strList) {
// 得到没有中文的字符串数组,中文已切除
String[] strarray = path.split("[\u4e00-\u9fa5]+");
StringBuilder sb = new StringBuilder();
if (strarray.length == strList.size()) {// 最后中文结尾的情况
for (int i = 0; i < strList.size(); i++) {
try {
sb.append(strarray[i] + URLEncoder.encode(strList.get(i), "UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
} else {// 里面有中文的情况
for (int i = 0; i < strList.size(); i++) {
try {
sb.append(strarray[i] + URLEncoder.encode(strList.get(i), "UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
sb.append(strarray[strarray.length - 1]);
}
return sb.toString();
}
/**
* 判断 昵称匹配规则
*
* @param nickName
* @return
*/
public static boolean isNickNameMatchRule(String nickName) {
int len = nickName.length();
for (int i = 0; i < len; i++) {
String str = nickName.substring(i, i + 1);
if (isChinese(str) || isUsualCharacter(str)) {
continue;
} else {
return false;
}
}
return true;
}
/**
* 判断是否符合昵称的最小长度
*
* @param str
* @param len
* @return
*/
public static boolean checkNickNameMinLen(String str, int len) {
int chinaCount = getChineseCount(str);
int otherCount = str.length() - chinaCount;
if (otherCount + chinaCount * 2 < len)
return false;
return true;
}
/**
* 判断是否符合昵称的最大长度
*
* @param str
* @param len
* @return
*/
public static boolean checkNickNameMaxLen(String str, int len) {
int chinaCount = getChineseCount(str);
int otherCount = str.length() - chinaCount;
if (otherCount + chinaCount * 2 > len)
return false;
return true;
}
/**
* md5 加密
*
* @param url
* @return
*/
public static String getMD5Str(String url) {
try {
MessageDigest digest = MessageDigest.getInstance("MD5");
byte[] result = digest.digest(url.getBytes());
StringBuffer sb = new StringBuffer();
for (byte b : result) {
int i = b & 0xff;// 将字节转为整数
String hexString = Integer.toHexString(i);// 将整数转为16进制
if (hexString.length() == 1) {
hexString = "0" + hexString;// 如果长度等于1, 加0补位
}
sb.append(hexString);
}
return sb.append(sb.substring(0, 10)).reverse().toString();
} catch (NoSuchAlgorithmException ex) {
return url;
}
}
/**
* 检查是否是手机号
*
* @param phone
* @return
*/
public static boolean checkPhoneNumber(String phone) {
String str = "^(1[0-9])\\d{9}$";
Pattern p = Pattern.compile(str, Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher(phone);
boolean isMatches = m.matches();
return isMatches;
}
/**
* 判断是否是数字
*
* @param str
* @return
*/
public static boolean isNumeric(String str) {
Pattern pattern = Pattern.compile("[0-9]*");
return pattern.matcher(str).matches();
}
public static boolean isDouble(String str) {
try {
Double.parseDouble(str);
return true;
} catch (NumberFormatException ex) {
}
return false;
}
/**
* 得到文件名称
*
* @param str
* @return
*/
public static String getUrlFileName(String str) {
int Index = str.lastIndexOf("/");
return str.substring(Index + 1);
}
/**
* 获取版本信息
*
* @return
*/
public static String getVersionName(Context context) {
PackageManager pm = context.getPackageManager();
try {
PackageInfo info = pm.getPackageInfo(context.getPackageName(), 0);
String versionName = info.versionName;
return versionName;
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
return "";
}
public static String getDeviceInfo(Context context) {
// if (ContextCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_STATE)== PackageManager.PERMISSION_DENIED) {
// ToastUitl.showShort("请在设置中打开获取手机信息的权限");
// return "";
// }
return Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
// TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
// return tm.getDeviceId();
}
/**
* @param urlpath
* @return Bitmap
* 根据图片url获取图片对象
*/
private static Bitmap bitmap;
public static Bitmap getBitMBitmap(final String urlpath) {
new Thread(new Runnable() {
@Override
public void run() {
try {
URL url = new URL(urlpath);
URLConnection conn = url.openConnection();
conn.connect();
InputStream in = conn.getInputStream();
bitmap = BitmapFactory.decodeStream(in);
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
return bitmap;
}
/**
* 获得32长度UUID值
*
* @return
* @author lt
*/
public static String getUUID() {
return UUID.randomUUID().toString().replace("-", "");
}
/**
* 将给定的数据进行MD5加密
*
* @param data
* @return
* @author lt
*/
public static String getMD5Value(String data) {
try {
//1 获得加密算法
MessageDigest messageDigest = MessageDigest.getInstance("MD5");
//2 加密
byte[] md5ByteArray = messageDigest.digest(data.getBytes());
//3 将10进制 转换成16进制
return new BigInteger(1, md5ByteArray).toString(16);
} catch (Exception e) {
return data;
}
}
/**
* 获得指定文件的二级目录
*
* @param filename
* @return
* @author lt
*/
public static String getDir(String filename) {
if (filename == null) {
return null;
}
// 1 获得数据
int code = filename.hashCode();
//System.out.println(code);
// 2 第一层目录
int d1 = code & 0xf;
// 3 第二层目录
int d2 = (code >>> 4) & 0xf;
// return File.separator + d1 + File.separator + d2;
return "/" + d1 + "/" + d2;
}
/**
* 将dip或dp值转换为px值,保证尺寸大小不变
*
* @param dipValue
* @param (DisplayMetrics类中属性density)
* @return
*/
public static int dip2px(Context context, float dipValue) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (dipValue * scale + 0.5f);
}
public static String getFormatedDateTime(String pattern, long dateTime) {
SimpleDateFormat sDateFormat = new SimpleDateFormat(pattern);
return sDateFormat.format(new Date(dateTime + 0));
}
public static String string2Double(String pattern) {
String[] s = pattern.split("\\.");
if ("00".equals(s[1])) {
pattern = s[0];
}
return pattern;
}
/**
* 使用java正则表达式去掉多余的.与0
*
* @param s
* @return
*/
public static String subZeroAndDot(String s) {
if (s.indexOf(".") > 0) {
s = s.replaceAll("0+?$", "");//去掉多余的0
s = s.replaceAll("[.]$", "");//如最后一位是.则去掉
}
return s;
}
public static String getPhoneModel() {
// return android.os.Build.MODEL;
// List<String> models = new ArrayList<>();
// models.add("EVA-AL00");
// models.add("EVA-AL10");
// models.add("EVA-TL00");
// models.add("EVA-DL00");
// models.add("EVA-CL00");
// models.add("FRD-AL00");
// models.add("FRD-DL00");
// for (int i = 0;i<models.size();i++){
// if (android.os.Build.MODEL.equals(models.get(i))){
// return true;
// }
// }
// return false;
return android.os.Build.MODEL;
}
public static boolean shouldLimit() {
// return android.os.Build.MODEL;
List<String> models = new ArrayList<>();
models.add("EVA-AL00");
models.add("EVA-AL10");
models.add("EVA-TL00");
models.add("EVA-DL00");
models.add("EVA-CL00");
models.add("FRD-AL00");
models.add("FRD-DL00");
for (int i = 0; i < models.size(); i++) {
if (android.os.Build.MODEL.equals(models.get(i))) {
return true;
}
}
return false;
}
public static boolean isZero(String str) {
//如果是null或者“”直接返回true
if (TextUtils.isEmpty(str)) {
return true;
}
try {
if (Integer.parseInt(str) == 0) {
return true;
} else {
return false;
}
} catch (Exception e) {
//如果不能转换,返回false
return false;
}
}
}
版权声明:本文为博主原创文章,未经博主允许不得转载
网友评论