android应用框架搭建------工具类(StringUtils)

本文分享了作者在应用开发中积累的字符串操作经验,包括日期格式化、正则表达式匹配、数值转换、加密解密等实用工具方法。

在应用开发中,字符串的操作肯定是少不了的。这里是我的一些经验的积累,工具类没有过多的解释,大家看注释就行了。


import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Pattern;

import android.app.Activity;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Bundle;
import android.telephony.TelephonyManager;

/**
 * 字符串操作工具包
 */
public class StringUtils {
    private final static Pattern emailer = Pattern
            .compile("\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*");
    private final static Pattern phone = Pattern
            .compile("^((13[0-9])|170|(15[^4,\\D])|(18[0,5-9]))\\d{8}$");

    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");
        }
    };

    /**
     * 返回当前系统时间
     */
    public static String getDataTime(String format) {
        SimpleDateFormat df = new SimpleDateFormat(format);
        return df.format(new Date());
    }

    /**
     * 返回当前系统时间
     */
    public static String getDataTime() {
        return getDataTime("HH:mm");
    }

    /**
     * 毫秒值转换为mm:ss
     * 
     * @author kymjs
     * @param ms
     */
    public static String timeFormat(int ms) {
        StringBuilder time = new StringBuilder();
        time.delete(0, time.length());
        ms /= 1000;
        int s = ms % 60;
        int min = ms / 60;
        if (min < 10) {
            time.append(0);
        }
        time.append(min).append(":");
        if (s < 10) {
            time.append(0);
        }
        time.append(s);
        return time.toString();
    }

    /**
     * 将字符串转位日期类型
     * 
     * @return
     */
    public static Date toDate(String sdate) {
        try {
            return dateFormater.get().parse(sdate);
        } catch (ParseException e) {
            return null;
        }
    }

    /**
     * 判断给定字符串时间是否为今日
     * 
     * @param sdate
     * @return boolean
     */
    public static boolean isToday(String sdate) {
        boolean b = false;
        Date time = toDate(sdate);
        Date today = new Date();
        if (time != null) {
            String nowDate = dateFormater2.get().format(today);
            String timeDate = dateFormater2.get().format(time);
            if (nowDate.equals(timeDate)) {
                b = true;
            }
        }
        return b;
    }

    /**
     * 判断给定字符串是否空白串 空白串是指由空格、制表符、回车符、换行符组成的字符串 若输入字符串为null或空字符串,返回true
     */
    public static boolean isEmpty(String input) {
        if (input == null || "".equals(input))
            return true;

        for (int i = 0; i < input.length(); i++) {
            char c = input.charAt(i);
            if (c != ' ' && c != '\t' && c != '\r' && c != '\n') {
                return false;
            }
        }
        return true;
    }

    /**
     * 判断是不是一个合法的电子邮件地址
     */
    public static boolean isEmail(String email) {
        if (email == null || email.trim().length() == 0)
            return false;
        return emailer.matcher(email).matches();
    }

    /**
     * 判断是不是一个合法的手机号码
     */
    public static boolean isPhone(String phoneNum) {
        if (phoneNum == null || phoneNum.trim().length() == 0)
            return false;
        return phone.matcher(phoneNum).matches();
    }

    /**
     * 字符串转整数
     * 
     * @param str
     * @param defValue
     * @return
     */
    public static int toInt(String str, int defValue) {
        try {
            return Integer.parseInt(str);
        } catch (Exception e) {
        }
        return defValue;
    }

    /**
     * 对象转整
     * 
     * @param obj
     * @return 转换异常返回 0
     */
    public static int toInt(Object obj) {
        if (obj == null)
            return 0;
        return toInt(obj.toString(), 0);
    }

    /**
     * String转long
     * 
     * @param obj
     * @return 转换异常返回 0
     */
    public static long toLong(String obj) {
        try {
            return Long.parseLong(obj);
        } catch (Exception e) {
        }
        return 0;
    }

    /**
     * String转double
     * 
     * @param obj
     * @return 转换异常返回 0
     */
    public static double toDouble(String obj) {
        try {
            return Double.parseDouble(obj);
        } catch (Exception e) {
        }
        return 0D;
    }

    /**
     * 字符串转布尔
     * 
     * @param b
     * @return 转换异常返回 false
     */
    public static boolean toBool(String b) {
        try {
            return Boolean.parseBoolean(b);
        } catch (Exception e) {
        }
        return false;
    }

    /**
     * 判断一个字符串是不是数字
     */
    public static boolean isNumber(String str) {
        try {
            Integer.parseInt(str);
        } catch (Exception e) {
            return false;
        }
        return true;
    }

    /**
     * 获取AppKey
     */
    public static String getMetaValue(Context context, String metaKey) {
        Bundle metaData = null;
        String apiKey = null;
        if (context == null || metaKey == null) {
            return null;
        }
        try {
            ApplicationInfo ai = context.getPackageManager()
                    .getApplicationInfo(context.getPackageName(),
                            PackageManager.GET_META_DATA);
            if (null != ai) {
                metaData = ai.metaData;
            }
            if (null != metaData) {
                apiKey = metaData.getString(metaKey);
            }
        } catch (NameNotFoundException e) {

        }
        return apiKey;
    }

    /**
     * 获取手机IMEI码
     */
    public static String getPhoneIMEI(Activity aty) {
        TelephonyManager tm = (TelephonyManager) aty
                .getSystemService(Activity.TELEPHONY_SERVICE);
        return tm.getDeviceId();
    }

    /**
     * MD5加密
     */
    public static String md5(String string) {
        byte[] hash;
        try {
            hash = MessageDigest.getInstance("MD5").digest(
                    string.getBytes("UTF-8"));
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("Huh, MD5 should be supported?", e);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException("Huh, UTF-8 should be supported?", e);
        }

        StringBuilder hex = new StringBuilder(hash.length * 2);
        for (byte b : hash) {
            if ((b & 0xFF) < 0x10)
                hex.append("0");
            hex.append(Integer.toHexString(b & 0xFF));
        }
        return hex.toString();
    }

    /**
     * KJ加密
     */
    public static String KJencrypt(String str) {
        char[] cstr = str.toCharArray();
        StringBuilder hex = new StringBuilder();
        for (char c : cstr) {
            hex.append((char) (c + 5));
        }
        return hex.toString();
    }

    /**
     * KJ解密
     */
    public static String KJdecipher(String str) {
        char[] cstr = str.toCharArray();
        StringBuilder hex = new StringBuilder();
        for (char c : cstr) {
            hex.append((char) (c - 5));
        }
        return hex.toString();
    }
}

这些是本人在工作中对于字符串操作的一些积累,有什么不足的地方还希望大家补充

转载于:https://my.oschina.net/kymjs/blog/221854

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、付费专栏及课程。

余额充值