android StringUtils

  1 import android.text.TextUtils;
  2 
  3 import java.text.DecimalFormat;
  4 import java.text.NumberFormat;
  5 import java.text.ParseException;
  6 import java.text.SimpleDateFormat;
  7 import java.util.Calendar;
  8 import java.util.GregorianCalendar;
  9 import java.util.Hashtable;
 10 import java.util.regex.Matcher;
 11 import java.util.regex.Pattern;
 12 
 13 public class StringUtils {
 14 
 15     private StringUtils() {
 16         /* cannot be instantiated */
 17         throw new UnsupportedOperationException("cannot be instantiated");
 18     }
 19 
 20     /**
 21      * 理财
 22      *计算收益
 23      * 产品利率
 24      * 期数
 25      * 本金
 26      */
 27     public static <T, E, Z> double countGraduation(T rate, E productCycle, Z money) {
 28         Double mRate;
 29         Double mProductCycle;
 30         Double mMoney;
 31         try {
 32             mRate = Double.parseDouble(rate + "");
 33             mProductCycle = Double.parseDouble(productCycle + "");
 34             mMoney = Double.parseDouble(money + "");
 35         } catch (Exception e) {
 36             return 0.00;
 37         }
 38 
 39         Double a = Arith.mul(mMoney, mRate);
 40         Double b = Arith.div(mProductCycle, 100);
 41         Double c = Arith.div(b, 12);
 42         Double d = Arith.mul(a, c);
 43 //        Double k = mMoney * mRate * mProductCycle/12/100;
 44         Double k = Arith.round(d, 2);
 45 
 46         return k;
 47     }
 48 
 49     /**
 50      * 优选
 51      *计算收益
 52      * 产品利率
 53      * 期数
 54      * 本金
 55      */
 56     public static <T, E, Z> double count(T rate, E productCycle, Z money) {
 57         Double mRate;
 58         Double mProductCycle;
 59         Double mMoney;
 60         try {
 61             mRate = Double.parseDouble(rate + "");
 62             mProductCycle = Double.parseDouble(productCycle + "");
 63             mMoney = Double.parseDouble(money + "");
 64         } catch (Exception e) {
 65             return 0.00;
 66         }
 67 
 68         Double a = Arith.div(mRate, 100);
 69         Double b = Arith.div(a, 12);
 70         Double c = Arith.add(1, b);
 71         Double d = Math.pow(c, mProductCycle);
 72         Double e = Arith.sub(d, 1);
 73         Double f = Arith.mul(mMoney, b);
 74         Double g = Arith.mul(f, d);
 75         Double h = Arith.div(g, e);
 76         Double i = Arith.mul(h, mProductCycle);
 77         Double j = Arith.sub(i, mMoney);
 78         Double k = Arith.round(j, 2);
 79 
 80         return k;
 81     }
 82     /**
 83      * 判断字符串是否为纯数字
 84      * 
 85      * @param str
 86      * @return
 87      */
 88     public static boolean isNumeric(String str) {
 89         Pattern pattern = Pattern.compile("[0-9]*");
 90         return pattern.matcher(str).matches();
 91     }
 92     
 93     /**
 94      * 判断是否为纯字母
 95      * @param str
 96      * @return
 97      */
 98     public static boolean isAlphabet(String str) {
 99         Pattern pattern = Pattern.compile("[a-zA-Z]");
100         return pattern.matcher(str).matches();
101     }
102 
103     /**
104      * 判断是否为纯汉字
105      * @param str
106      * @return
107      */
108     public static boolean isChineseCharacters(String str) {
109         Pattern pattern = Pattern.compile("[\u4e00-\u9fa5]");
110         return pattern.matcher(str).matches();
111 
112     }
113 
114     /**
115      * 判断是否为手机号
116      * 
117      * @param mobiles
118      * @return
119      */
120     public static boolean isPhone(String mobiles) {
121         String str = "^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1})|(17[0-9]{1})|(14[0-9]{1}))+\\d{8})$";
122         Pattern p = Pattern.compile(str);
123         Matcher m = p.matcher(mobiles);
124         return m.matches();
125     }
126     
127     /**
128      * 判断密码是否符合生产密码的条件,不能是纯数字,不能输纯字母,数字加字母结合的6到16位的
129      * 
130      * @param password
131      *            密码
132      */
133     public static boolean isPassword(String password) {
134         Pattern p = Pattern
135                 .compile("^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,20}$");
136         Matcher m = p.matcher(password);
137         return m.matches();
138     }
139     
140     /**
141      * 去掉特殊字符
142      * 
143      * @param str
144      * @return
145      */
146     public static boolean isExcptional(String str) {
147         String regEx = "[`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~!@#¥%……&*()——+|{}【】‘;:”“’。,、?]";
148         Pattern p = Pattern.compile(regEx);
149         Matcher m = p.matcher(str);
150         return m.matches();
151     }
152     
153     /**
154      * 设置模糊手机号码
155      * 
156      * @param phone
157      * @return
158      */
159     public static String setBlurryPhone(String phone) {
160         if (TextUtils.isEmpty(phone)) {
161             return "";
162         } else {
163             int length = phone.length();
164             String blurryPhone=null;
165             if (length>=11) {
166                 blurryPhone=phone.substring(0, length-(length-3)) + "******"+ phone.substring((length-2), length);
167             }else{
168                 blurryPhone="";
169             }
170             return blurryPhone;
171         }
172     }
173     
174     /**
175      * 格式化钱(1000.208---->1,000.21)
176      * 
177      * @param moneyStr
178      *            需要转换的金额
179      * @return 格式化后的金额
180      */
181     public static String moneyFormat(String moneyStr) {
182         if (moneyStr == null || moneyStr.equals("")) {
183             return "0.00";
184         }
185         double money = Double.valueOf(moneyStr);
186         NumberFormat nf = new DecimalFormat("#,##0.00");
187         String testStr = nf.format(money);
188         return testStr;
189     }
190 //身份证号码验证:start
191     /**
192      * 功能:身份证的有效验证
193      * @param IDStr 身份证号
194      * @return 有效:返回"" 无效:返回String信息
195      * @throws
196      */
197     public static String IDCardValidate(String IDStr) throws ParseException {
198         String errorInfo = "";// 记录错误信息
199         String[] ValCodeArr = { "1", "0", "x", "9", "8", "7", "6", "5", "4",
200                 "3", "2" };
201         String[] Wi = { "7", "9", "10", "5", "8", "4", "2", "1", "6", "3", "7",
202                 "9", "10", "5", "8", "4", "2" };
203         String Ai = "";
204         // ================ 号码的长度 15位或18位 ================
205         if (IDStr.length() != 15 && IDStr.length() != 18) {
206             errorInfo = "身份证号码长度应该为15位或18位。";
207             return errorInfo;
208         }
209         // =======================(end)========================
210 
211         // ================ 数字 除最后以为都为数字 ================
212         if (IDStr.length() == 18) {
213             Ai = IDStr.substring(0, 17);
214         } else if (IDStr.length() == 15) {
215             Ai = IDStr.substring(0, 6) + "19" + IDStr.substring(6, 15);
216         }
217         if (isNumeric(Ai) == false) {
218             errorInfo = "身份证15位号码都应为数字 ; 18位号码除最后一位外,都应为数字。";
219             return errorInfo;
220         }
221         // =======================(end)========================
222 
223         // ================ 出生年月是否有效 ================
224         String strYear = Ai.substring(6, 10);// 年份
225         String strMonth = Ai.substring(10, 12);// 月份
226         String strDay = Ai.substring(12, 14);// 月份
227         if (isDataFormat(strYear + "-" + strMonth + "-" + strDay) == false) {
228             errorInfo = "身份证生日无效。";
229             return errorInfo;
230         }
231         GregorianCalendar gc = new GregorianCalendar();
232         SimpleDateFormat s = new SimpleDateFormat("yyyy-MM-dd");
233         if ((gc.get(Calendar.YEAR) - Integer.parseInt(strYear)) > 150
234                 || (gc.getTime().getTime() - s.parse(
235                 strYear + "-" + strMonth + "-" + strDay).getTime()) < 0) {
236             errorInfo = "身份证生日不在有效范围。";
237             return errorInfo;
238         }
239         if (Integer.parseInt(strMonth) > 12 || Integer.parseInt(strMonth) == 0) {
240             errorInfo = "身份证月份无效";
241             return errorInfo;
242         }
243         if (Integer.parseInt(strDay) > 31 || Integer.parseInt(strDay) == 0) {
244             errorInfo = "身份证日期无效";
245             return errorInfo;
246         }
247         // =====================(end)=====================
248 
249         // ================ 地区码时候有效 ================
250         Hashtable h = GetAreaCode();
251         if (h.get(Ai.substring(0, 2)) == null) {
252             errorInfo = "身份证地区编码错误。";
253             return errorInfo;
254         }
255         // ==============================================
256 
257         // ================ 判断最后一位的值 ================
258         int TotalmulAiWi = 0;
259         for (int i = 0; i < 17; i++) {
260             TotalmulAiWi = TotalmulAiWi
261                     + Integer.parseInt(String.valueOf(Ai.charAt(i)))
262                     * Integer.parseInt(Wi[i]);
263         }
264         int modValue = TotalmulAiWi % 11;
265         String strVerifyCode = ValCodeArr[modValue];
266         Ai = Ai + strVerifyCode;
267 
268         if (IDStr.length() == 18) {
269             if (Ai.equals(IDStr) == false) {
270                 errorInfo = "身份证无效,不是合法的身份证号码";
271                 return errorInfo;
272             }
273         } else {
274             return "";
275         }
276         // =====================(end)=====================
277         return "";
278     }
279 
280     /**
281      * 功能:设置地区编码
282      * @return Hashtable 对象
283      */
284     private static Hashtable GetAreaCode() {
285         Hashtable hashtable = new Hashtable();
286         hashtable.put("11", "北京");
287         hashtable.put("12", "天津");
288         hashtable.put("13", "河北");
289         hashtable.put("14", "山西");
290         hashtable.put("15", "内蒙古");
291         hashtable.put("21", "辽宁");
292         hashtable.put("22", "吉林");
293         hashtable.put("23", "黑龙江");
294         hashtable.put("31", "上海");
295         hashtable.put("32", "江苏");
296         hashtable.put("33", "浙江");
297         hashtable.put("34", "安徽");
298         hashtable.put("35", "福建");
299         hashtable.put("36", "江西");
300         hashtable.put("37", "山东");
301         hashtable.put("41", "河南");
302         hashtable.put("42", "湖北");
303         hashtable.put("43", "湖南");
304         hashtable.put("44", "广东");
305         hashtable.put("45", "广西");
306         hashtable.put("46", "海南");
307         hashtable.put("50", "重庆");
308         hashtable.put("51", "四川");
309         hashtable.put("52", "贵州");
310         hashtable.put("53", "云南");
311         hashtable.put("54", "西藏");
312         hashtable.put("61", "陕西");
313         hashtable.put("62", "甘肃");
314         hashtable.put("63", "青海");
315         hashtable.put("64", "宁夏");
316         hashtable.put("65", "新疆");
317         hashtable.put("71", "台湾");
318         hashtable.put("81", "香港");
319         hashtable.put("82", "澳门");
320         hashtable.put("91", "国外");
321         return hashtable;
322     }
323     /**验证日期字符串是否是YYYY-MM-DD格式
324      * @param str
325      * @return
326      */
327     public static boolean isDataFormat(String str){
328         boolean flag=false;
329         //String regxStr="[1-9][0-9]{3}-[0-1][0-2]-((0[1-9])|([12][0-9])|(3[01]))";
330         String regxStr="^((\\d{2}(([02468][048])|([13579][26]))[\\-\\/\\s]?((((0?[13578])|(1[02]))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])))))|(\\d{2}(([02468][1235679])|([13579][01345789]))[\\-\\/\\s]?((((0?[13578])|(1[02]))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-\\/\\s]?((0?[1-9])|(1[0-9])|(2[0-8]))))))(\\s(((0?[0-9])|([1-2][0-3]))\\:([0-5]?[0-9])((\\s)|(\\:([0-5]?[0-9])))))?$";
331         Pattern pattern1=Pattern.compile(regxStr);
332         Matcher isNo=pattern1.matcher(str);
333         if(isNo.matches()){
334             flag=true;
335         }
336         return flag;
337     }
338 }
View Code

 

转载于:https://www.cnblogs.com/annieBaby/p/6635557.html

1、HttpUtils Http网络工具类,主要包括httpGet、httpPost以及http参数相关方法,以httpGet为例: static HttpResponse httpGet(HttpRequest request) static HttpResponse httpGet(java.lang.String httpUrl) static String httpGetString(String httpUrl) 包含以上三个方法,默认使用gzip压缩,使用bufferedReader提高读取速度。 HttpRequest中可以设置url、timeout、userAgent等其他http参数 HttpResponse中可以获取返回内容、http响应码、http过期时间(Cache-Control的max-age和expires)等 前两个方法可以进行高级参数设置及丰富内容返回,第三个方法可以简单的传入url获取返回内容,httpPost类似。更详细的设置可以直接使用HttpURLConnection或apache的HttpClient。 源码可见HttpUtils.java,更多方法及更详细参数介绍可见HttpUtils Api Guide。 2、DownloadManagerPro Android系统下载管理DownloadManager增强方法,可用于包括获取下载相关信息,如: getStatusById(long) 得到下载状态 getDownloadBytes(long) 得到下载进度信息 getBytesAndStatus(long) 得到下载进度信息和状态 getFileName(long) 得到下载文件路径 getUri(long) 得到下载uri getReason(long) 得到下载失败或暂停原因 getPausedReason(long) 得到下载暂停原因 getErrorCode(long) 得到下载错误码 源码可见DownloadManagerPro.java,更多方法及更详细参数介绍可见DownloadManagerPro Api Guide。关于Android DownManager使用可见DownManager Demo。 3、ShellUtils Android Shell工具类,可用于检查系统root权限,并在shell或root用户下执行shell命令。如: checkRootPermission() 检查root权限 execCommand(String[] commands, boolean isRoot, boolean isNeedResultMsg) shell环境执行命令,第二个参数表示是否root权限执行 execCommand(String command, boolean isRoot) shell环境执行命令 源码可见ShellUtils.java,更多方法及更详细参数介绍可见ShellUtils Api Guide。关于静默安装可见apk-root权限静默安装。 4、PackageUtils Android包相关工具类,可用于(root)安装应用、(root)卸载应用、判断是否系统应用等,如: install(Context, String) 安装应用,如果是系统应用或已经root,则静默安装,否则一般安装 uninstall(Context, String) 卸载应用,如果是系统应用或已经root,则静默卸载,否则一般卸载 isSystemApplication(Context, String) 判断应用是否为系统应用 源码可见PackageUtils.java,更多方法及更详细参数介绍可见ShellUtils Api Guide。关于静默安装可见apk-root权限静默安装。 5、PreferencesUtils Android SharedPreferences相关工具类,可用于方便的向SharedPreferences中读取和写入相关类型数据,如: putString(Context, String, String) 保存string类型数据 putInt(Context, String, int) 保存int类型数据 getString(Context, String) 获取string类型数据 getInt(Context, String) 获取int类型数据 可通过修改PREFERENCE_NAME变量修改preference name 源码可见PreferencesUtils.java,更多方法及更详细参数介绍可见PreferencesUtils Api Guide。 6、JSONUtils JSONUtils工具类,可用于方便的向Json中读取和写入相关类型数据,如: String getString(JSONObject jsonObject, String key, String defaultValue) 得到string类型value String getString(String jsonData, String key, String defaultValue) 得到string类型value 表示从json中读取某个String类型key的值 getMap(JSONObject jsonObject, String key) 得到map getMap(String jsonData, String key) 得到map 表示从json中读取某个Map类型key的值 源码可见JSONUtils.java,更多方法及更详细参数介绍可见JSONUtils Api Guide。 7、FileUtils 文件工具类,可用于读写文件及对文件进行操作。如: readFile(String filePath) 读文件 writeFile(String filePath, String content, boolean append) 写文件 getFileSize(String path) 得到文件大小 deleteFile(String path) 删除文件 源码可见FileUtils.java,更多方法及更详细参数介绍可见FileUtils Api Guide。 8、ResourceUtils Android Resource工具类,可用于从android资源目录的raw和assets目录读取内容,如: geFileFromAssets(Context context, String fileName) 得到assets目录下某个文件内容 geFileFromRaw(Context context, int resId) 得到raw目录下某个文件内容 源码可见ResourceUtils.java,更多方法及更详细参数介绍可见ResourceUtils Api Guide。 9、StringUtils String工具类,可用于常见字符串操作,如: isEmpty(String str) 判断字符串是否为空或长度为0 isBlank(String str) 判断字符串是否为空或长度为0 或由空格组成 utf8Encode(String str) 以utf-8格式编码 capitalizeFirstLetter(String str) 首字母大写 源码可见StringUtils.java,更多方法及更详细参数介绍可见StringUtils Api Guide。 10、ParcelUtils Android Parcel工具类,可用于从parcel读取或写入特殊类型数据,如: readBoolean(Parcel in) 从pacel中读取boolean类型数据 readHashMap(Parcel in, ClassLoader loader) 从pacel中读取map类型数据 writeBoolean(boolean b, Parcel out) 向parcel中写入boolean类型数据 writeHashMap(Map map, Parcel out, int flags) 向parcel中写入map类型数据 源码可见ParcelUtils.java,更多方法及更详细参数介绍可见ParcelUtils Api Guide。 11、RandomUtils 随机数工具类,可用于获取固定大小固定字符内的随机数,如: getRandom(char[] sourceChar, int length) 生成随机字符串,所有字符均在某个字符串内 getRandomNumbers(int length) 生成随机数字 源码可见RandomUtils.java,更多方法及更详细参数介绍可见RandomUtils Api Guide。 12、ArrayUtils 数组工具类,可用于数组常用操作,如: isEmpty(V[] sourceArray) 判断数组是否为空或长度为0 getLast(V[] sourceArray, V value, V defaultValue, boolean isCircle) 得到数组中某个元素前一个元素,isCircle表示是否循环 getNext(V[] sourceArray, V value, V defaultValue, boolean isCircle) 得到数组中某个元素下一个元素,isCircle表示是否循环 源码可见ArrayUtils.java,更多方法及更详细参数介绍可见ArrayUtils Api Guide。 13、ImageUtils 图片工具类,可用于Bitmap, byte array, Drawable之间进行转换以及图片缩放,目前功能薄弱,后面会进行增强。如: bitmapToDrawable(Bitmap b) bimap转换为drawable drawableToBitmap(Drawable d) drawable转换为bitmap drawableToByte(Drawable d) drawable转换为byte scaleImage(Bitmap org, float scaleWidth, float scaleHeight) 缩放图片 源码可见ImageUtils.java,更多方法及更详细参数介绍可见ImageUtils Api Guide。 14、ListUtils List工具类,可用于List常用操作,如: isEmpty(List sourceList) 判断List是否为空或长度为0 join(List list, String separator) List转换为字符串,并以固定分隔符分割 addDistinctEntry(List sourceList, V entry) 向list中添加不重复元素 源码可见ListUtils.java,更多方法及更详细参数介绍可见ListUtils Api Guide。 15、MapUtils Map工具类,可用于Map常用操作,如: isEmpty(Map sourceMap) 判断map是否为空或长度为0 parseKeyAndValueToMap(String source, String keyAndValueSeparator, String keyAndValuePairSeparator, boolean ignoreSpace) 字符串解析为map toJson(Map map) map转换为json格式 源码可见MapUtils.java,更多方法及更详细参数介绍可见MapUtils Api Guide。 16、ObjectUtils Object工具类,可用于Object常用操作,如: isEquals(Object actual, Object expected) 比较两个对象是否相等 compare(V v1, V v2) 比较两个对象大小 transformIntArray(int[] source) Integer 数组转换为int数组 源码可见ObjectUtils.java,更多方法及更详细参数介绍可见ObjectUtils Api Guide。 17、SerializeUtils 序列化工具类,可用于序列化对象到文件或从文件反序列化对象,如: deserialization(String filePath) 从文件反序列化对象 serialization(String filePath, Object obj) 序列化对象到文件 源码可见SerializeUtils.java,更多方法及更详细参数介绍可见SerializeUtils Api Guide。 18、SystemUtils 系统信息工具类,可用于得到线程池合适的大小,目前功能薄弱,后面会进行增强。如: getDefaultThreadPoolSize() 得到跟系统配置相符的线程池大小 源码可见SystemUtils.java,更多方法及更详细参数介绍可见SystemUtils Api Guide。 19、TimeUtils 时间工具类,可用于时间相关操作,如: getCurrentTimeInLong() 得到当前时间 getTime(long timeInMillis, SimpleDateFormat dateFormat) 将long转换为固定格式时间字符串 源码可见TimeUtils.java,更多方法及更详细参数介绍可见TimeUtils Api Guide。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值