博客源址:
工具类有:AppUtil、BitmapUtil、DateUtil、JsonUtil、LogUtil、MeasureUtil、NetWorkUtil、PreferencesUtil、ReflectUtil、SDCardUtil、ScreenUtil、XmlUtil、ColorUtil、ExitActivityUtil、FileUtil、HttpUtil、PhoneUtil、ShortCutUtil、
AppUtil工具类:
BitmapUtil工具类:
- import java.io.ByteArrayOutputStream;
-
- import android.content.Context;
- import android.graphics.Bitmap;
- import android.graphics.Bitmap.CompressFormat;
- import android.graphics.BitmapFactory;
- import android.graphics.BitmapFactory.Options;
- import android.graphics.Canvas;
- import android.graphics.PixelFormat;
- import android.graphics.drawable.BitmapDrawable;
- import android.graphics.drawable.Drawable;
- import android.media.ThumbnailUtils;
- import android.text.TextUtils;
-
-
-
-
- public class BitmapUtil {
-
- private BitmapUtil(){}
-
-
-
-
-
-
-
-
-
- public static Bitmap getBitmapFromResource(Context context, int id, int height, int width){
- Options options = new Options();
- options.inJustDecodeBounds = true;
- BitmapFactory.decodeResource(context.getResources(), id, options);
- options.inSampleSize = calculateSampleSize(height, width, options);
- options.inJustDecodeBounds = false;
- Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), id, options);
- return bitmap;
- }
-
-
-
-
-
-
-
-
- public static Bitmap getBitmapFromFile(String path, int height, int width){
- if (TextUtils.isEmpty(path)) {
- throw new IllegalArgumentException("参数为空,请检查你选择的路径:" + path);
- }
- Options options = new Options();
- options.inJustDecodeBounds = true;
- BitmapFactory.decodeFile(path, options);
- options.inSampleSize = calculateSampleSize(height, width, options);
- options.inJustDecodeBounds = false;
- Bitmap bitmap = BitmapFactory.decodeFile(path, options);
- return bitmap;
- }
-
-
-
-
-
-
-
-
- public static Bitmap getThumbnailsBitmap(Bitmap bitmap, int height, int width){
- if (bitmap == null) {
- throw new IllegalArgumentException("图片为空,请检查你的参数");
- }
- return ThumbnailUtils.extractThumbnail(bitmap, width, height);
- }
-
-
-
-
-
-
-
- public static Drawable bitmapToDrawable(Context context, Bitmap bitmap){
- if (context == null || bitmap == null) {
- throw new IllegalArgumentException("参数不合法,请检查你的参数");
- }
- Drawable drawable = new BitmapDrawable(context.getResources(), bitmap);
- return drawable;
- }
-
-
-
-
-
-
- public static Bitmap drawableToBitmap(Drawable drawable) {
- if (drawable == null) {
- throw new IllegalArgumentException("Drawable为空,请检查你的参数");
- }
- Bitmap bitmap =
- Bitmap.createBitmap(drawable.getIntrinsicWidth(),
- drawable.getIntrinsicHeight(),
- drawable.getOpacity() != PixelFormat.OPAQUE? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565);
- Canvas canvas = new Canvas(bitmap);
- drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
- drawable.draw(canvas);
- return bitmap;
- }
-
-
-
-
-
-
- public static byte[] bitmapToByte(Bitmap bitmap){
- if (bitmap == null) {
- throw new IllegalArgumentException("Bitmap为空,请检查你的参数");
- }
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- bitmap.compress(CompressFormat.PNG, 100, baos);
- return baos.toByteArray();
- }
-
-
-
-
-
-
-
-
- private static int calculateSampleSize(int height, int width, Options options){
- int realHeight = options.outHeight;
- int realWidth = options.outWidth;
- int heigthScale = realHeight / height;
- int widthScale = realWidth / width;
- if(widthScale > heigthScale){
- return widthScale;
- }else{
- return heigthScale;
- }
- }
- }
DateUtil工具类:
- import java.text.ParseException;
- import java.text.SimpleDateFormat;
- import java.util.Calendar;
- import java.util.Date;
- import java.util.Locale;
-
- public class DateUtil {
-
- private DateUtil(){}
-
-
-
-
- public enum DatePattern{
-
-
-
- ALL_TIME{public String getValue(){return "yyyy-MM-dd HH:mm:ss";}},
-
-
-
- ONLY_MONTH{public String getValue(){return "yyyy-MM";}},
-
-
-
- ONLY_DAY{public String getValue(){return "yyyy-MM-dd";}},
-
-
-
- ONLY_HOUR{public String getValue(){return "yyyy-MM-dd HH";}},
-
-
-
- ONLY_MINUTE{public String getValue(){return "yyyy-MM-dd HH:mm";}},
-
-
-
- ONLY_MONTH_DAY{public String getValue(){return "MM-dd";}},
-
-
-
- ONLY_MONTH_SEC{public String getValue(){return "MM-dd HH:mm";}},
-
-
-
- ONLY_TIME{public String getValue(){return "HH:mm:ss";}},
-
-
-
- ONLY_HOUR_MINUTE{public String getValue(){return "HH:mm";}};
- public abstract String getValue();
- }
-
-
-
-
-
- public static String getNowDate(DatePattern pattern){
- String dateString = null;
- Calendar calendar = Calendar.getInstance();
- Date dateNow = calendar.getTime();
- SimpleDateFormat sdf = new SimpleDateFormat(pattern.getValue(),Locale.CHINA);
- dateString = sdf.format(dateNow);
- return dateString;
- }
-
-
-
-
-
-
-
- public static Date stringToDate(String dateString, DatePattern pattern){
- Date date = null;
- SimpleDateFormat sdf = new SimpleDateFormat(pattern.getValue(),Locale.CHINA);
- try {
- date = sdf.parse(dateString);
- } catch (ParseException e) {
- e.printStackTrace();
- }
- return date;
- }
-
-
-
-
-
-
-
- public static String dateToString(Date date, DatePattern pattern){
- String string = "";
- SimpleDateFormat sdf = new SimpleDateFormat(pattern.getValue(), Locale.CHINA);
- string = sdf.format(date);
- return string;
- }
-
-
-
-
-
-
-
- public static String getWeekOfDate(Date date){
- String[] weekDays = { "周日", "周一", "周二", "周三", "周四", "周五", "周六" };
- Calendar calendar = Calendar.getInstance();
- calendar.setTime(date);
- int week = calendar.get(Calendar.DAY_OF_WEEK) - 1;
- if (week < 0)
- week = 0;
- return weekDays[week];
- }
-
-
-
-
-
-
- public static int getIndexWeekOfDate(Date date){
- Calendar calendar = Calendar.getInstance();
- calendar.setTime(date);
- int index = calendar.get(Calendar.DAY_OF_WEEK);
- if(index == 1){
- return 7;
- }else{
- return --index;
- }
- }
-
-
-
-
-
- public static int getNowMonth(){
- Calendar calendar = Calendar.getInstance();
- return calendar.get(Calendar.MONTH) + 1;
- }
-
-
-
-
-
- public static int getNowDay(){
- Calendar calendar = Calendar.getInstance();
- return calendar.get(Calendar.DATE);
- }
-
-
-
-
-
- public static int getNowYear(){
- Calendar calendar = Calendar.getInstance();
- return calendar.get(Calendar.YEAR);
- }
-
-
-
-
-
- public static int getNowDaysOfMonth(){
- Calendar calendar = Calendar.getInstance();
- return daysOfMonth(calendar.get(Calendar.YEAR),calendar.get(Calendar.DATE) + 1);
- }
-
-
-
-
-
-
-
- public static int daysOfMonth(int year,int month){
- switch(month){
- case 1:
- case 3:
- case 5:
- case 7:
- case 8:
- case 10:
- case 12:
- return 31;
- case 4:
- case 6:
- case 9:
- case 11:
- return 30;
- case 2:
- if((year % 4 ==0 && year % 100 == 0) || year % 400 != 0){
- return 29;
- }else{
- return 28;
- }
- default:
- return -1;
- }
- }
- }
JsonUtil工具类:
- import java.util.Iterator;
- import java.util.List;
-
- import org.json.JSONArray;
- import org.json.JSONException;
- import org.json.JSONObject;
-
- import android.content.ContentValues;
-
- import com.google.gson.Gson;
-
-
-
-
- public class JsonUtil {
-
- private JsonUtil(){}
-
- private static Gson gson = new Gson();
-
-
-
-
-
-
- public static <T> String objectToJson(T t){
- if (t instanceof String) {
- return t.toString();
- } else {
- return gson.toJson(t);
- }
- }
-
-
-
-
-
-
-
- @SuppressWarnings("unchecked")
- public static<T> T jsonToObject(String jsonString, Class<T> clazz){
- if (clazz == String.class) {
- return (T) jsonString;
- } else {
- return (T)gson.fromJson(jsonString, clazz);
- }
- }
-
-
-
-
-
-
- public static<T> String listToJson(List<T> list){
- JSONArray jsonArray = new JSONArray();
- JSONObject jsonObject = null;
- try {
- for (int i = 0; i < list.size(); i++) {
- jsonObject = new JSONObject(objectToJson(list.get(i)));
- jsonArray.put(jsonObject);
- }
- } catch (JSONException e) {
- e.printStackTrace();
- } finally {
- if (jsonObject != null) {
- jsonObject = null;
- }
- }
- return jsonArray.toString();
- }
-
-
-
-
-
-
- public static<T> String arrayToJson(T[] array){
- JSONArray jsonArray = new JSONArray();
- JSONObject jsonObject = null;
- try {
- for (int i = 0; i < array.length; i++) {
- jsonObject = new JSONObject(objectToJson(array[i]));
- jsonArray.put(jsonObject);
- }
- } catch (JSONException e) {
- e.printStackTrace();
- } finally {
- if (jsonObject != null) {
- jsonObject = null;
- }
- }
- return jsonArray.toString();
- }
-
-
-
-
-
-
-
-
- public static<T> T getJsonObjectValue(String json, String key, Class<T> clazz){
- try {
- return getJsonObjectValue(new JSONObject(json), key, clazz);
- } catch (JSONException e) {
- e.printStackTrace();
- }
- return null;
- }
-
-
-
-
-
-
-
-
- @SuppressWarnings("unchecked")
- public static<T> T getJsonObjectValue(JSONObject jsonObject, String key, Class<T> clazz){
- T t = null;
- try {
- if (clazz == Integer.class) {
- t = (T) Integer.valueOf(jsonObject.getInt(key));
- }else if(clazz == Boolean.class){
- t = (T) Boolean.valueOf(jsonObject.getBoolean(key));
- }else if(clazz == String.class){
- t = (T) String.valueOf(jsonObject.getString(key));
- }else if(clazz == Double.class){
- t = (T) Double.valueOf(jsonObject.getDouble(key));
- }else if(clazz == JSONObject.class){
- t = (T) jsonObject.getJSONObject(key);
- }else if(clazz == JSONArray.class){
- t = (T) jsonObject.getJSONArray(key);
- }else if(clazz == Long.class){
- t = (T) Long.valueOf(jsonObject.getLong(key));
- }
- } catch (JSONException e) {
- e.printStackTrace();
- }
- return t;
- }
-
-
-
-
-
-
- @SuppressWarnings("rawtypes")
- public static ContentValues jsonToContentValues(String json){
- ContentValues contentValues = new ContentValues();
- try {
- JSONObject jsonObject = new JSONObject(json);
- Iterator iterator = jsonObject.keys();
- String key;
- Object value;
- while (iterator.hasNext()) {
- key = iterator.next().toString();
- value = jsonObject.get(key);
- String valueString = value.toString();
- if (value instanceof String) {
- contentValues.put(key, valueString);
- }else if(value instanceof Integer){
- contentValues.put(key, Integer.valueOf(valueString));
- }else if(value instanceof Long){
- contentValues.put(key, Long.valueOf(valueString));
- }else if(value instanceof Double){
- contentValues.put(key, Double.valueOf(valueString));
- }else if(value instanceof Float){
- contentValues.put(key, Float.valueOf(valueString));
- }else if(value instanceof Boolean){
- contentValues.put(key, Boolean.valueOf(valueString));
- }
- }
- } catch (JSONException e) {
- e.printStackTrace();
- throw new Error("Json字符串不合法:" + json);
- }
-
- return contentValues;
- }
- }
LogUtil工具类:
- import android.util.Log;
-
-
-
-
- public class LogUtil {
-
- private LogUtil(){}
-
-
-
-
-
-
- public static void i(String tag,String msg){
- Log.i(tag, msg);
- }
-
-
-
-
-
-
-
- public static void i(String tag, String msg, Throwable throwable){
- Log.i(tag,msg,throwable);
- }
-
-
-
-
-
-
- public static void v(String tag, String msg){
- Log.v(tag, msg);
- }
-
-
-
-
-
-
-
- public static void v(String tag, String msg, Throwable throwable){
- Log.v(tag, msg, throwable);
- }
-
-
-
-
-
-
- public static void d(String tag, String msg){
- Log.d(tag, msg);
- }
-
-
-
-
-
-
-
- public static void d(String tag, String msg, Throwable throwable){
- Log.d(tag, msg, throwable);
- }
-
-
-
-
-
-
- public static void w(String tag, String msg){
- Log.w(tag, msg);
- }
-
-
-
-
-
-
-
- public static void w(String tag, String msg, Throwable throwable){
- Log.w(tag, msg, throwable);
- }
-
-
-
-
-
-
- public static void e(String tag, String msg){
- Log.e(tag, msg);
- }
-
-
-
-
-
-
-
- public static void e(String tag, String msg, Throwable throwable){
- Log.e(tag, msg, throwable);
- }
- }
MeasureUtil工具类:
- import android.content.Context;
- import android.view.View;
- import android.view.ViewGroup;
- import android.widget.Adapter;
- import android.widget.GridView;
- import android.widget.ListView;
-
-
-
-
- public class MeasureUtil {
-
- private MeasureUtil(){}
-
-
-
-
-
-
- public static int getMeasuredHeight(View view) {
- if (view == null) {
- throw new IllegalArgumentException("view is null");
- }
- view.measure(0, 0);
- return view.getMeasuredHeight();
- }
-
-
-
-
-
-
- public static int getHeight(View view){
- if(view == null){
- throw new IllegalArgumentException("view is null");
- }
-
- view.measure(0, 0);
- return view.getHeight();
- }
-
-
-
-
-
-
- public static int getMeasuredWidth(View view){
- if(view == null){
- throw new IllegalArgumentException("view is null");
- }
-
- view.measure(0, 0);
- return view.getMeasuredWidth();
- }
-
-
-
-
-
-
- public static int getWidth(View view){
- if(view == null){
- throw new IllegalArgumentException("view is null");
- }
-
- view.measure(0, 0);
- return view.getWidth();
- }
-
-
-
-
-
-
- public static void setHeight(View view, int height) {
- if (view == null || view.getLayoutParams() == null) {
- throw new IllegalArgumentException("View LayoutParams is null");
- }
- ViewGroup.LayoutParams params = view.getLayoutParams();
- params.height = height;
- view.setLayoutParams(params);
- }
-
-
-
-
-
-
- public static void setWidth(View view, int width){
- if(view == null || view.getLayoutParams() == null){
- throw new IllegalArgumentException("View LayoutParams is null");
- }
-
- ViewGroup.LayoutParams params = view.getLayoutParams();
- params.width = width;
- view.setLayoutParams(params);
- }
-
-
-
-
-
- public static void setListHeight(ListView listView) {
- if (listView == null) {
- throw new IllegalArgumentException("ListView is null");
- }
- Adapter adapter = listView.getAdapter();
- if (adapter == null) {
- return;
- }
- int totalHeight = 0;
- int size = adapter.getCount();
- for (int i = 0; i < size; i++) {
- View listItem = adapter.getView(i, null, listView);
- listItem.measure(0, 0);
- totalHeight += listItem.getMeasuredHeight();
- }
- ViewGroup.LayoutParams params = listView.getLayoutParams();
- params.height = totalHeight + (listView.getDividerHeight() * (size - 1));
- LogUtil.d("MeasureUtil", "listview-height--" + params.height);
- listView.setLayoutParams(params);
- }
-
-
-
-
-
-
-
-
- public static void setGridViewHeight(Context context, GridView gv, int n, int m) {
- if(gv == null){
- throw new IllegalArgumentException("GridView is null");
- }
- Adapter adapter = gv.getAdapter();
- if (adapter == null) {
- return;
- }
- int totalHeight = 0;
- int size = adapter.getCount();
- for (int i = 0; i < size; i++) {
- View listItem = adapter.getView(i, null, gv);
- listItem.measure(0, 0);
- totalHeight += listItem.getMeasuredHeight() + ScreenUtil.dp2px(context, m);
- }
- ViewGroup.LayoutParams params = gv.getLayoutParams();
- params.height = totalHeight + gv.getPaddingTop() + gv.getPaddingBottom() + 2;
- LogUtil.d("MeasureUtil", "gridview-height--" + params.height);
- gv.setLayoutParams(params);
- }
-
- }
NetWorkUtil工具类:
- import android.app.Activity;
- import android.content.ComponentName;
- import android.content.Context;
- import android.content.Intent;
- import android.net.ConnectivityManager;
- import android.net.NetworkInfo;
- import android.provider.Settings;
-
-
-
-
- public class NetWorkUtil {
-
-
-
-
-
-
- @SuppressWarnings("null")
- public static boolean isNetWorkEnable(Context context){
- ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
- NetworkInfo networkInfo = manager.getActiveNetworkInfo();
- if (networkInfo != null || networkInfo.isConnected()) {
- if (networkInfo.getState() == NetworkInfo.State.CONNECTED) {
- return true;
- }
- }
- return false;
- }
-
-
-
-
-
-
- @SuppressWarnings("static-access")
- public static boolean isWiFiConnected(Context context){
- ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
- NetworkInfo networkInfo = manager.getActiveNetworkInfo();
- return networkInfo.getType() == manager.TYPE_WIFI ? true : false;
- }
-
-
-
-
-
-
-
- public static boolean isMobileDataEnable(Context context){
- ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
- boolean isMobileDataEnable = false;
- isMobileDataEnable = manager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).isConnectedOrConnecting();
- return isMobileDataEnable;
- }
-
-
-
-
-
-
-
- public static boolean isWifiDataEnable(Context context){
- ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
- boolean isWifiDataEnable = false;
- isWifiDataEnable = manager.getNetworkInfo(
- ConnectivityManager.TYPE_WIFI).isConnectedOrConnecting();
- return isWifiDataEnable;
- }
-
-
-
-
-
- public static void GoSetting(Activity activity){
- Intent intent = new Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS);
- activity.startActivity(intent);
- }
-
-
-
-
- public static void openSetting(Activity activity) {
- Intent intent = new Intent("/");
- ComponentName cn = new ComponentName("com.android.settings", "com.android.settings.WirelessSettings");
- intent.setComponent(cn);
- intent.setAction("android.intent.action.VIEW");
- activity.startActivityForResult(intent, 0);
- }
- }
PreferencesUtil工具类:
- import java.lang.reflect.InvocationTargetException;
- import java.lang.reflect.Method;
- import java.util.Map;
- import java.util.Set;
-
- import android.content.Context;
- import android.content.SharedPreferences;
- import android.content.SharedPreferences.Editor;
-
-
-
-
- public class PreferencesUtil {
-
- private PreferencesUtil(){}
-
-
-
-
- private static final String SHARED_NAME = "SharedPreferences";
-
-
-
-
-
-
-
- public static boolean containsKey(Context context, String key){
- SharedPreferences sp = getSharedPreferences(context);
- return sp.contains(key);
- }
-
-
-
-
-
-
- public static Map<String, ?> getAll(Context context) {
- SharedPreferences sp = getSharedPreferences(context);
- return sp.getAll();
- }
-
-
-
-
-
-
-
-
- public static Object get(Context context, String key, Object defaultObject){
- SharedPreferences sp = getSharedPreferences(context);
- if (defaultObject instanceof String) {
- return sp.getString(key, (String) defaultObject);
- } else if (defaultObject instanceof Integer) {
- return sp.getInt(key, (Integer) defaultObject);
- } else if (defaultObject instanceof Boolean) {
- return sp.getBoolean(key, (Boolean) defaultObject);
- } else if (defaultObject instanceof Float) {
- return sp.getFloat(key, (Float) defaultObject);
- } else if (defaultObject instanceof Long) {
- return sp.getLong(key, (Long) defaultObject);
- }
- return null;
- }
-
-
-
-
-
-
-
-
- public static Set<String> getStringSet(Context context, String key, Set<String> defValues){
- SharedPreferences sp = getSharedPreferences(context);
- return sp.getStringSet(key, defValues);
- }
-
-
-
-
-
-
-
-
- public static boolean putStringSet(Context context, String key, Set<String> value){
- return getEditor(context).putStringSet(key, value).commit();
- }
-
-
-
-
-
-
-
-
- public static void put(Context context, String key, Object object){
- if (object instanceof String) {
- getEditor(context).putString(key, (String) object);
- } else if (object instanceof Integer) {
- getEditor(context).putInt(key, (Integer) object);
- } else if (object instanceof Boolean) {
- getEditor(context).putBoolean(key, (Boolean) object);
- } else if (object instanceof Float) {
- getEditor(context).putFloat(key, (Float) object);
- } else if (object instanceof Long) {
- getEditor(context).putLong(key, (Long) object);
- } else {
- getEditor(context).putString(key, object.toString());
- }
- SharedPreferencesCompat.apply(getEditor(context));
- }
-
-
-
-
-
-
-
-
- public static void removeKey(Context context, String key){
- getEditor(context).remove(key);
- SharedPreferencesCompat.apply(getEditor(context));
- }
-
-
-
-
-
- public static void clearValues(Context context){
- getEditor(context).clear();
- SharedPreferencesCompat.apply(getEditor(context));
- }
-
-
-
-
-
-
- private static SharedPreferences getSharedPreferences(Context context){
- return context.getSharedPreferences(SHARED_NAME, Context.MODE_PRIVATE);
- }
-
-
-
-
-
-
- private static Editor getEditor(Context context){
- return getSharedPreferences(context).edit();
- }
-
-
-
-
- private static class SharedPreferencesCompat {
- private static final Method sApplyMethod = findApplyMethod();
-
-
-
-
-
- @SuppressWarnings({ "unchecked", "rawtypes" })
- private static Method findApplyMethod() {
- try {
- Class clz = SharedPreferences.Editor.class;
- return clz.getMethod("apply");
- } catch (NoSuchMethodException e) {
- e.printStackTrace();
- }
- return null;
- }
-
-
-
-
-
- public static void apply(SharedPreferences.Editor editor) {
- try {
- if (sApplyMethod != null) {
- sApplyMethod.invoke(editor);
- return;
- }
- } catch (IllegalArgumentException e) {
- e.printStackTrace();
- } catch (IllegalAccessException e) {
- e.printStackTrace();
- } catch (InvocationTargetException e) {
- e.printStackTrace();
- }
- editor.commit();
- }
- }
- }
ReflectUtil工具类:
- import java.lang.reflect.Field;
- import java.lang.reflect.Method;
- import java.lang.reflect.Modifier;
- import java.lang.reflect.Type;
-
- import android.text.TextUtils;
-
-
-
-
- public class ReflectUtil {
-
- private ReflectUtil(){}
-
-
-
-
-
-
-
-
- public static<T> void setFieldValue(T t,Field field, String fieldName, String value){
- String name = field.getName();
-
- if (!fieldName.equals(name)) {
- return;
- }
-
- Type type = field.getType();
-
- int typeCode = field.getModifiers();
-
- String typeName = type.toString();
- try {
- switch (typeName) {
- case "class java.lang.String":
- if (Modifier.isPublic(typeCode)) {
- field.set(t, value);
- } else {
- Method method = t.getClass().getMethod("set" + getMethodName(fieldName), String.class);
- method.invoke(t, value);
- }
- break;
- case "double":
- if(Modifier.isPublic(typeCode)){
- field.setDouble(t, Double.valueOf(value));
- }else{
- Method method = t.getClass().getMethod("set" + getMethodName(fieldName),double.class);
- method.invoke(t, Double.valueOf(value));
- }
- break;
- case "int":
- if(Modifier.isPublic(typeCode)){
- field.setInt(t, Integer.valueOf(value));
- }else{
- Method method = t.getClass().getMethod("set" + getMethodName(fieldName),int.class);
- method.invoke(t, Integer.valueOf(value));
- }
- break;
- case "float":
- if(Modifier.isPublic(typeCode)){
- field.setFloat(t, Float.valueOf(value));
- }else{
- Method method = t.getClass().getMethod("set" + getMethodName(fieldName), float.class);
- method.invoke(t, Float.valueOf(value));
- }
- break;
- }
- } catch (IllegalAccessException e) {
- e.printStackTrace();
- } catch (IllegalArgumentException e) {
- e.printStackTrace();
- } catch (NoSuchMethodException e) {
- e.printStackTrace();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
-
-
-
-
-
-
-
- private static String getMethodName(String fieldName) throws Exception{
- byte[] items = fieldName.getBytes();
- items[0] = (byte) ((char)items[0] - 'a' + 'A');
- return new String(items);
- }
-
-
-
-
-
-
-
- public static Field getField(Class<?> clazz, String filedName){
- if (clazz == null || TextUtils.isEmpty(filedName)) {
- throw new IllegalArgumentException("params is illegal");
- }
- Field[] fields = clazz.getDeclaredFields();
- return getFieldByName(fields, filedName);
- }
-
-
-
-
-
-
-
- public static Field getFieldByName(Field[] fields, String fieldName){
- if (fields == null || fields.length == 0 || TextUtils.isEmpty(fieldName)) {
- throw new IllegalArgumentException("params is illegal");
- }
- for (Field field : fields) {
- String name = field.getName();
-
- if (fieldName.equals(name)) {
- return field;
- }
- }
- return null;
- }
-
-
-
-
-
-
-
- public static boolean isFiledWithName(Field field, String fieldName){
- if(field == null || TextUtils.isEmpty(fieldName)){
- throw new IllegalArgumentException("params is illegal");
- }
- if (fieldName.equals(field.getName())) {
- return true;
- }
- return false;
- }
- }
SDCardUtil工具类:
ScreenUtil工具类:
- import android.app.Activity;
- import android.content.Context;
- import android.graphics.Bitmap;
- import android.graphics.Rect;
- import android.util.DisplayMetrics;
- import android.view.View;
- import android.view.WindowManager;
-
-
-
-
- public class ScreenUtil {
-
- private ScreenUtil(){}
-
-
-
-
-
-
- public static int getScreenWidth(Context context){
- return getDisplayMetrics(context).widthPixels;
- }
-
-
-
-
-
-
- public static int getScreenHeight(Context context){
- return getDisplayMetrics(context).heightPixels;
- }
-
-
-
-
-
-
- public static float getDensity(Context context){
- return getDisplayMetrics(context).density;
- }
-
-
-
-
-
-
- public static float getScaledDensity(Context context){
- return getDisplayMetrics(context).scaledDensity;
- }
-
-
-
-
-
-
-
- public static int dp2px(Context context, int dpValue){
- return (int) (dpValue * getDensity(context) + 0.5f);
- }
-
-
-
-
-
-
-
- public static int px2dp(Context context, int pxValue){
- return (int) (pxValue / getDensity(context) + 0.5f);
- }
-
-
-
-
-
-
-
- public static int sp2px(Context context, int spValue){
- return (int) (spValue * getScaledDensity(context) + 0.5f);
- }
-
-
-
-
-
-
-
- public static int px2sp(Context context, int pxValue){
- return (int) (pxValue / getScaledDensity(context) + 0.5f);
- }
-
-
-
-
-
-
-
- public static int getStatusHeight(Context context){
- int statusHeight = -1;
- try {
- Class<?> clazz = Class.forName("com.android.internal.R$dimen");
- Object object = clazz.newInstance();
- int height = Integer.parseInt(clazz.getField("status_bar_height").get(object).toString());
- statusHeight = context.getResources().getDimensionPixelSize(height);
- } catch (Exception e) {
- e.printStackTrace();
- }
- return statusHeight;
- }
-
-
-
-
-
-
- public static Bitmap snapShotWithStatusBar(Activity activity){
- View decorView = activity.getWindow().getDecorView();
- decorView.setDrawingCacheEnabled(true);
- decorView.buildDrawingCache();
- Bitmap bmp = decorView.getDrawingCache();
- int width = getScreenWidth(activity);
- int height = getScreenHeight(activity);
- Bitmap bitmap = null;
- bitmap = Bitmap.createBitmap(bmp, 0, 0, width, height);
- decorView.destroyDrawingCache();
- return bitmap;
- }
-
-
-
-
-
-
- public static Bitmap snapShotWithoutStatusBar(Activity activity){
- View decorView = activity.getWindow().getDecorView();
- decorView.setDrawingCacheEnabled(true);
- decorView.buildDrawingCache();
- Bitmap bmp = decorView.getDrawingCache();
- Rect frame = new Rect();
- activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
- int statusHeight = frame.top;
-
- int width = getScreenWidth(activity);
- int height = getScreenHeight(activity);
- Bitmap bitmap = null;
- bitmap = Bitmap.createBitmap(bmp, 0, statusHeight, width, height - statusHeight);
- decorView.destroyDrawingCache();
- return bitmap;
- }
-
-
-
-
-
-
- public static DisplayMetrics getDisplayMetrics(Context context){
- WindowManager manager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
- DisplayMetrics metrics = new DisplayMetrics();
- manager.getDefaultDisplay().getMetrics(metrics);
- return metrics;
- }
- }
XmlUtil工具类:
- import java.io.ByteArrayInputStream;
- import java.io.IOException;
- import java.io.InputStream;
- import java.lang.reflect.Field;
- import java.util.ArrayList;
- import java.util.List;
-
- import org.xmlpull.v1.XmlPullParser;
- import org.xmlpull.v1.XmlPullParserException;
-
- import android.text.TextUtils;
- import android.util.Xml;
-
-
-
-
- public class XMLUtil {
-
- private XMLUtil(){}
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- public static<T> List<T> xmlToObject(String xml, Class<T> clazz, String tagEntity){
- List<T> list = null;
- XmlPullParser xmlPullParser = Xml.newPullParser();
- InputStream inputStream = new ByteArrayInputStream(xml.getBytes());
- try {
- xmlPullParser.setInput(inputStream, "utf-8");
- Field[] fields = clazz.getDeclaredFields();
- int type = xmlPullParser.getEventType();
- String lastTag = "";
- T t = null;
- while (type != XmlPullParser.END_DOCUMENT) {
- switch (type) {
- case XmlPullParser.START_DOCUMENT:
- list = new ArrayList<T>();
- break;
- case XmlPullParser.START_TAG:
- String tagName = xmlPullParser.getName();
- if(tagEntity.equals(tagName)){
- t = clazz.newInstance();
- lastTag = tagEntity;
- }else if(tagEntity.equals(lastTag)){
- String textValue = xmlPullParser.nextText();
- String fieldName = xmlPullParser.getName();
- for(Field field : fields){
- ReflectUtil.setFieldValue(t,field,fieldName,textValue);
- }
- }
- break;
- case XmlPullParser.END_TAG:
- tagName = xmlPullParser.getName();
- if(tagEntity.equals(tagName)){
- list.add(t);
- lastTag = "";
- }
- break;
- case XmlPullParser.END_DOCUMENT:
- break;
- }
- }
- } catch (XmlPullParserException e) {
- e.printStackTrace();
- } catch (InstantiationException e) {
- e.printStackTrace();
- } catch (IllegalAccessException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }
- return list;
- }
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- public static<T> List<T> attributeToObject(String xml, Class<T> clazz, String tagName){
- if(TextUtils.isEmpty(tagName))return null;
- List<T> list = null;
- XmlPullParser xmlPullParser = Xml.newPullParser();
- InputStream inputStream = new ByteArrayInputStream(xml.getBytes());
- try {
- xmlPullParser.setInput(inputStream, "utf-8");
- int type = xmlPullParser.getEventType();
- T t = null;
- while(type != XmlPullParser.END_DOCUMENT){
- switch(type){
- case XmlPullParser.START_DOCUMENT:
- list = new ArrayList<T>();
- break;
- case XmlPullParser.START_TAG:
- if(tagName.equals(xmlPullParser.getName())){
- t = clazz.newInstance();
- Field[] fields = clazz.getDeclaredFields();
- for(Field field : fields){
- String fieldName = field.getName();
- for(int index = 0;index < xmlPullParser.getAttributeCount();index++){
- if(fieldName.equals(xmlPullParser.getAttributeName(index))){
- ReflectUtil.setFieldValue(t,field,fieldName,xmlPullParser.getAttributeValue(index));
- }
- }
- }
- }
- break;
- case XmlPullParser.END_TAG:
- if(tagName.equals(xmlPullParser.getName())){
- list.add(t);
- }
- break;
- case XmlPullParser.END_DOCUMENT:
- break;
- }
- type = xmlPullParser.next();
- }
- }catch(Exception ex){
- ex.printStackTrace();
- }
- return list;
-
- }
-
-
-
-
-
-
-
-
- public static String getTagAttribute(String xml, String tagName, String attributeName){
- if(TextUtils.isEmpty(tagName) || TextUtils.isEmpty(attributeName)){
- throw new IllegalArgumentException("请填写标签名称或属性名称");
- }
- XmlPullParser xmlPullParser = Xml.newPullParser();
- InputStream inputStream = new ByteArrayInputStream(xml.getBytes());
- try {
- xmlPullParser.setInput(inputStream, "utf-8");
- int type = xmlPullParser.getEventType();
- while(type != XmlPullParser.END_DOCUMENT){
- switch(type){
- case XmlPullParser.START_TAG:
- if(tagName.equals(xmlPullParser.getName())){
- for(int i=0; i < xmlPullParser.getAttributeCount();i++){
- if(attributeName.equals(xmlPullParser.getAttributeName(i))){
- return xmlPullParser.getAttributeValue(i);
- }
- }
- }
- break;
- }
- type = xmlPullParser.next();
- }
- } catch (XmlPullParserException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }
- return null;
- }
- }
ColorUtil工具类:
ExitActivityUtil工具类:
- import android.app.Activity;
- import android.view.KeyEvent;
- import android.widget.Toast;
-
- public class ExitActivityUtil extends Activity{
-
- private long exitTime = 0;
-
-
-
-
- @Override
- public boolean onKeyDown(int keyCode, KeyEvent event) {
- if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
-
- if((System.currentTimeMillis() - exitTime) > 2000){
- Toast.makeText(getApplicationContext(), "再按一次退出程序", Toast.LENGTH_SHORT).show();
- exitTime = System.currentTimeMillis();
- } else {
- finish();
- System.exit(0);
- }
- return true;
- }
- return super.onKeyDown(keyCode, event);
- }
-
- }
FileUtil工具类:
- import java.io.File;
- import java.io.FileInputStream;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import java.io.InputStream;
-
-
-
-
- public class FileUtil {
-
-
-
-
-
-
-
- public static void mkFile(String filePath, boolean mkdir) throws IOException{
- File file = new File(filePath);
-
-
-
-
-
- file.getParentFile().mkdirs();
- file.createNewFile();
- file = null;
- }
-
-
-
-
-
-
- public static boolean mkDir(String dirPath) {
- return new File(dirPath).mkdirs();
- }
-
-
-
-
-
-
- public static boolean delFile(String filePath) {
- return new File(filePath).delete();
- }
-
-
-
-
-
-
-
- public static boolean delDir(String dirPath, boolean delFile) {
- if (delFile) {
- File file = new File(dirPath);
- if (file.isFile()) {
- return file.delete();
- } else if (file.isDirectory()) {
- if (file.listFiles().length == 0) {
- return file.delete();
- } else {
- int zFiles = file.listFiles().length;
- File[] delfile = file.listFiles();
- for (int i = 0; i < zFiles; i++) {
- if (delfile[i].isDirectory()) {
- delDir(delfile[i].getAbsolutePath(), true);
- }
- delfile[i].delete();
- }
- return file.delete();
- }
- } else {
- return false;
- }
- } else {
- return new File(dirPath).delete();
- }
- }
-
-
-
-
-
-
-
-
- public static void copy(String source, String target, boolean isFolder) throws IOException{
- if (isFolder) {
- new File(target).mkdirs();
- File a = new File(source);
- String[] file = a.list();
- File temp = null;
- for (int i = 0; i < file.length; i++) {
- if (source.endsWith(File.separator)) {
- temp = new File(source + file[i]);
- } else {
- temp = new File(source + File.separator + file[i]);
- }
- if (temp.isFile()) {
- FileInputStream input = new FileInputStream(temp);
- FileOutputStream output = new FileOutputStream(target + File.separator + temp.getName().toString());
- byte[] b = new byte[1024];
- int len;
- while ((len = input.read(b)) != -1) {
- output.write(b, 0, len);
- }
- output.flush();
- output.close();
- input.close();
- } if (temp.isDirectory()) {
- copy(source + File.separator + file[i], target + File.separator + file[i], true);
- }
- }
- } else {
- int byteread = 0;
- File oldfile = new File(source);
- if (oldfile.exists()) {
- InputStream inputStream = new FileInputStream(source);
- File file = new File(target);
- file.getParentFile().mkdirs();
- file.createNewFile();
- FileOutputStream outputStream = new FileOutputStream(file);
- byte[] buffer = new byte[1024];
- while ((byteread = inputStream.read(buffer)) != -1){
- outputStream.write(buffer, 0, byteread);
- }
- inputStream.close();
- outputStream.close();
- }
- }
- }
- }
HttpUtil工具类:
- import java.io.BufferedReader;
- import java.io.ByteArrayOutputStream;
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.InputStreamReader;
- import java.io.PrintWriter;
- import java.net.HttpURLConnection;
- import java.net.MalformedURLException;
- import java.net.URL;
-
-
-
-
- public class HttpUtil {
-
- private static final int TIMEOUT_IN_MILLIONS = 5000;
-
- public interface CallBack {
- void onRequestComplete(String requst);
- }
-
-
-
-
-
-
- public static void doGetAsyn(final String urlStr, final CallBack callBack) {
- new Thread(new Runnable() {
-
- @Override
- public void run() {
- try {
- String result = doGet(urlStr);
- if (callBack != null) {
- callBack.onRequestComplete(result);
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }).start();
- }
-
-
-
-
-
-
-
-
- public static void doPostAsyn(final String urlStr, final String params,
- final CallBack callBack) {
- new Thread(new Runnable() {
- @Override
- public void run() {
- try {
- String result = doPost(urlStr, params);
- if (callBack != null) {
- callBack.onRequestComplete(result);
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }).start();
- }
-
-
-
-
-
-
-
-
-
- public static String doGet(String urlStr) {
- URL url = null;
- HttpURLConnection conn = null;
- InputStream is = null;
- ByteArrayOutputStream baos = null;
- try {
- url = new URL(urlStr);
- conn = (HttpURLConnection) url.openConnection();
- conn.setReadTimeout(TIMEOUT_IN_MILLIONS);
- conn.setConnectTimeout(TIMEOUT_IN_MILLIONS);
- conn.setRequestMethod("GET");
- conn.setRequestProperty("accept", "*/*");
- conn.setRequestProperty("connection", "Keep-Alive");
- if (conn.getResponseCode() == 200) {
- is = conn.getInputStream();
- baos = new ByteArrayOutputStream();
- int len = -1;
- byte[] buf = new byte[1024];
- while ((len = is.read()) != -1) {
- baos.write(buf, 0, len);
- }
- baos.flush();
- return baos.toString();
- } else {
- throw new RuntimeException(" responseCode is not 200 ... ");
- }
- } catch (MalformedURLException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- } finally {
- try {
- if (is != null)
- is.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- try {
- if (baos != null)
- baos.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- conn.disconnect();
- }
- return null;
- }
-
- /**
- * 向指定 URL 发送POST方法的请求
- * @param url 发送请求的 URL
- * @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
- * @return 所代表远程资源的响应结果
- * @throws Exception
- */
- public static String doPost(String url, String param) {
- PrintWriter out = null;
- BufferedReader in = null;
- String result = "";
- try {
- URL realUrl = new URL(url);
- HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();
-
- conn.setRequestProperty("accept", "*/*");
- conn.setRequestProperty("connection", "Keep-Alive");
- conn.setRequestMethod("POST");
- conn.setRequestProperty("accept", "*/*");
- conn.setRequestProperty("connection", "Keep-Alive");
- conn.setRequestMethod("POST");
- conn.setRequestProperty("Content-Type",
- "application/x-www-form-urlencoded");
- conn.setRequestProperty("charset", "utf-8");
- conn.setUseCaches(false);
-
- conn.setDoOutput(true);
- conn.setDoInput(true);
- conn.setReadTimeout(TIMEOUT_IN_MILLIONS);
- conn.setConnectTimeout(TIMEOUT_IN_MILLIONS);
- if (param != null && !param.trim().equals("")) {
-
- out = new PrintWriter(conn.getOutputStream());
-
- out.print(param);
-
- out.flush();
- }
-
- in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
- String line;
- while ((line = in.readLine()) != null) {
- result += line;
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
-
- finally {
- try {
- if (out != null) {
- out.close();
- }
- if (in != null) {
- in.close();
- }
- } catch (IOException ex) {
- ex.printStackTrace();
- }
- }
- return result;
- }
-
- }
PhoneUtil工具类:
- import java.io.File;
-
- import android.app.Activity;
- import android.content.Context;
- import android.content.Intent;
- import android.net.Uri;
- import android.provider.MediaStore;
-
-
-
-
- public class PhoneUtil {
-
- private static long lastClickTime;
-
- private PhoneUtil() {
- throw new Error("Do not need instantiate!");
- }
-
-
-
-
-
-
-
- public static void sendMessage(Context activity, String phoneNumber, String smsContent) {
- if (smsContent == null || phoneNumber.length() < 4) {
- return;
- }
- Uri uri = Uri.parse("smsto:" + phoneNumber);
- Intent intent = new Intent(Intent.ACTION_SENDTO, uri);
- intent.putExtra("sms_body", smsContent);
- intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
- activity.startActivity(intent);
- }
-
-
-
-
-
- public static boolean isFastDoubleClick() {
- long time = System.currentTimeMillis();
- long timeD = time - lastClickTime;
- if (0 < timeD && timeD < 500) {
- return true;
- }
- lastClickTime = time;
- return false;
- }
-
-
-
-
-
-
- public static String getMobileModel(Context context) {
- try {
- String model = android.os.Build.MODEL;
- return model;
- } catch (Exception e) {
- return "未知!";
- }
- }
-
-
-
-
-
-
- public static String getMobileBrand(Context context) {
- try {
-
- String brand = android.os.Build.BRAND;
- return brand;
- } catch (Exception e) {
- return "未知";
- }
- }
-
-
-
-
-
-
-
- public static void toTakePhoto(int requestcode, Activity activity,String fileName) {
- Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
- intent.putExtra("camerasensortype", 2);
- intent.putExtra("autofocus", true);
- intent.putExtra("fullScreen", false);
- intent.putExtra("showActionIcons", false);
- try {
-
- File file = new File(fileName);
-
- if (!file.exists()) {
- file.mkdirs();
- }
- Uri uri = Uri.fromFile(file);
- intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
- activity.startActivityForResult(intent, requestcode);
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
-
-
-
-
-
-
- public static void toTakePicture(int requestcode, Activity activity){
- Intent intent = new Intent(Intent.ACTION_PICK, null);
- intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
- activity.startActivityForResult(intent, requestcode);
- }
- }
ShortCutUtil工具类:
- import android.app.Activity;
- import android.content.ComponentName;
- import android.content.ContentResolver;
- import android.content.Intent;
- import android.database.Cursor;
- import android.net.Uri;
-
-
-
-
-
-
- public class ShortCutUtil {
-
- private ShortCutUtil() {
- throw new Error("Do not need instantiate!");
- }
-
-
-
-
-
-
- public static boolean hasShortcut(Activity activity) {
- boolean isInstallShortcut = false;
- ContentResolver cr = activity.getContentResolver();
- String AUTHORITY = "com.android.launcher.settings";
- Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY
- + "/favorites?notify=true");
- Cursor c = cr.query(CONTENT_URI,
- new String[]{"title", "iconResource"}, "title=?",
- new String[]{activity.getString(R.string.app_name).trim()},
- null);
- if (c != null && c.getCount() > 0) {
- isInstallShortcut = true;
- }
-
- return isInstallShortcut;
- }
-
-
-
-
-
-
- public static void addShortcut(Activity activity,int res) {
- Intent shortcut = new Intent(
- "com.android.launcher.action.INSTALL_SHORTCUT");
-
- shortcut.putExtra(Intent.EXTRA_SHORTCUT_NAME,
- activity.getString(R.string.app_name));
-
- shortcut.putExtra("duplicate", false);
- Intent shortcutIntent = new Intent(Intent.ACTION_MAIN);
- shortcutIntent.setClassName(activity, activity.getClass().getName());
- shortcut.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
-
- Intent.ShortcutIconResource iconRes =
- Intent.ShortcutIconResource.fromContext(activity, res);
- shortcut.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, iconRes);
- activity.sendBroadcast(shortcut);
- }
-
-
-
-
-
- public static void delShortcut(Activity activity) {
- Intent shortcut = new Intent(
- "com.android.launcher.action.UNINSTALL_SHORTCUT");
- shortcut.putExtra(Intent.EXTRA_SHORTCUT_NAME,
- activity.getString(R.string.app_name));
- String appClass = activity.getPackageName() + "."
- + activity.getLocalClassName();
- ComponentName cn = new ComponentName(activity.getPackageName(), appClass);
- shortcut.putExtra(Intent.EXTRA_SHORTCUT_INTENT, new Intent(
- Intent.ACTION_MAIN).setComponent(cn));
- activity.sendBroadcast(shortcut);
- }
- }
StringUtil工具类:
- import java.io.UnsupportedEncodingException;
- import java.net.URLEncoder;
- import java.security.MessageDigest;
- import java.util.ArrayList;
- import java.util.Locale;
- import java.util.regex.Matcher;
- import java.util.regex.Pattern;
-
-
-
-
- public class StringUtil {
-
- private StringUtil() {
- throw new AssertionError();
- }
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- public static boolean isBlank(String str) {
- return (str == null || str.trim().length() == 0);
- }
-
-
-
-
-
-
-
-
-
-
-
- public static boolean isEmpty(CharSequence c) {
- return (c == null || c.length() == 0);
- }
-
-
-
-
-
-
-
-
-
-
-
-
- public static int length(CharSequence c) {
- return c == null ? 0 : c.length();
- }
-
-
-
-
-
-
-
-
-
-
-
-
-
- public static String nullStrToEmpty(Object object) {
- return object == null ?
- "" : (object instanceof String ? (String)object : object.toString());
- }
-
-
-
-
-
- public static String capitalizeFirstLetter(String str) {
- if (isEmpty(str)) {
- return str;
- }
- char c = str.charAt(0);
- return (!Character.isLetter(c) || Character.isUpperCase(c))
- ? str
- : new StringBuilder(str.length()).append(
- Character.toUpperCase(c))
- .append(str.substring(1))
- .toString();
- }
-
-
-
-
-
-
- public static String utf8Encode(String str) {
- if (!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;
- }
-
-
-
-
-
- public static String getHrefInnerHtml(String href) {
- if (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;
- }
-
-
-
-
-
- public static String htmlEscapeCharsToString(String source) {
- return StringUtil.isEmpty(source)
- ? source
- : source.replaceAll("<", "<")
- .replaceAll(">", ">")
- .replaceAll("&", "&")
- .replaceAll(""", "\"");
- }
-
-
-
-
-
- public static String fullWidthToHalfWidth(String s) {
- if (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] >= 65281 && source[i] <= 65374) {
- source[i] = (char) (source[i] - 65248);
- }
- else {
- source[i] = source[i];
- }
- }
- return new String(source);
- }
-
-
-
-
-
- public static String halfWidthToFullWidth(String s) {
-
- if (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] >= 33 && source[i] <= 126) {
- source[i] = (char) (source[i] + 65248);
- }
- else {
- source[i] = source[i];
- }
- }
- return new String(source);
- }
-
-
-
-
-
-
-
- public static String replaceBlanktihuan(String str) {
-
- String dest = "";
- if (str != null) {
- Pattern p = Pattern.compile("\\s*|\t|\r|\n");
- Matcher m = p.matcher(str);
- dest = m.replaceAll("");
- }
- return dest;
- }
-
-
-
-
-
-
- public static boolean isEmpty(String string) {
- return string == null || "".equals(string.trim());
- }
-
-
-
-
-
-
- public static boolean isNotEmpty(String string) {
- return !isEmpty(string);
- }
-
-
-
-
-
-
- public static boolean isEmpty(String... strings) {
- boolean result = true;
- for (String string : strings) {
- if (isNotEmpty(string)) {
- result = false;
- break;
- }
- }
- return result;
- }
-
-
-
-
-
-
-
-
- public static boolean isNotEmpty(String... strings) {
- boolean result = true;
- for (String string : strings) {
- if (isEmpty(string)) {
- result = false;
- break;
- }
- }
- return result;
- }
-
-
-
-
-
- public static String filterEmpty(String string) {
- return StringUtil.isNotEmpty(string) ? string : "";
- }
-
-
-
-
-
-
-
-
-
- public static String replace(String string, char oldchar, char newchar) {
- char chars[] = string.toCharArray();
- for (int w = 0; w < chars.length; w++) {
- if (chars[w] == oldchar) {
- chars[w] = newchar;
- break;
- }
- }
- return new String(chars);
- }
-
-
-
-
-
-
-
-
- public static String[] split(String string, char ch) {
- ArrayList<String> stringList = new ArrayList<String>();
- char chars[] = string.toCharArray();
- int nextStart = 0;
- for (int w = 0; w < chars.length; w++) {
- if (ch == chars[w]) {
- stringList.add(new String(chars, nextStart, w - nextStart));
- nextStart = w + 1;
- if (nextStart ==
- chars.length) {
- stringList.add("");
- }
- }
- }
- if (nextStart <
- chars.length) {
- stringList.add(new String(chars, nextStart,
- chars.length - 1 - nextStart + 1));
- }
- return stringList.toArray(new String[stringList.size()]);
- }
-
-
-
-
-
-
-
-
- public static int countLength(String string) {
- int length = 0;
- char[] chars = string.toCharArray();
- for (int w = 0; w < string.length(); w++) {
- char ch = chars[w];
- if (ch >= '\u0391' && ch <= '\uFFE5') {
- length++;
- length++;
- }
- else {
- length++;
- }
- }
- return length;
- }
-
- private static char[] getChars(char[] chars, int startIndex) {
- int endIndex = startIndex + 1;
-
- if (Character.isDigit(chars[startIndex])) {
-
- while (endIndex < chars.length &&
- Character.isDigit(chars[endIndex])) {
- endIndex++;
- }
- }
- char[] resultChars = new char[endIndex - startIndex];
- System.arraycopy(chars, startIndex, resultChars, 0, resultChars.length);
- return resultChars;
- }
-
-
-
-
-
- public static boolean isAllDigital(char[] chars) {
- boolean result = true;
- for (int w = 0; w < chars.length; w++) {
- if (!Character.isDigit(chars[w])) {
- result = false;
- break;
- }
- }
- return result;
- }
-
-
-
-
-
-
-
-
-
-
-
- public static String removeChar(String string, char ch) {
- StringBuffer sb = new StringBuffer();
- for (char cha : string.toCharArray()) {
- if (cha != '-') {
- sb.append(cha);
- }
- }
- return sb.toString();
- }
-
-
-
-
-
-
-
-
- public static String removeChar(String string, int index) {
- String result = null;
- char[] chars = string.toCharArray();
- if (index == 0) {
- result = new String(chars, 1, chars.length - 1);
- }
- else if (index == chars.length - 1) {
- result = new String(chars, 0, chars.length - 1);
- }
- else {
- result = new String(chars, 0, index) +
- new String(chars, index + 1, chars.length - index);
- ;
- }
- return result;
- }
-
-
-
-
-
-
-
-
-
- public static String removeChar(String string, int index, char ch) {
- String result = null;
- char[] chars = string.toCharArray();
- if (chars.length > 0 && chars[index] == ch) {
- if (index == 0) {
- result = new String(chars, 1, chars.length - 1);
- }
- else if (index == chars.length - 1) {
- result = new String(chars, 0, chars.length - 1);
- }
- else {
- result = new String(chars, 0, index) +
- new String(chars, index + 1, chars.length - index);
- ;
- }
- }
- else {
- result = string;
- }
- return result;
- }
-
-
-
-
-
-
-
-
- public static String filterBlank(String string) {
- if ("".equals(string)) {
- return null;
- }
- else {
- return string;
- }
- }
-
-
-
-
-
-
-
-
-
-
- public static String toLowerCase(String str, int beginIndex, int endIndex) {
- return str.replaceFirst(str.substring(beginIndex, endIndex),
- str.substring(beginIndex, endIndex)
- .toLowerCase(Locale.getDefault()));
- }
-
-
-
-
-
-
-
-
-
-
- public static String toUpperCase(String str, int beginIndex, int endIndex) {
- return str.replaceFirst(str.substring(beginIndex, endIndex),
- str.substring(beginIndex, endIndex)
- .toUpperCase(Locale.getDefault()));
- }
-
-
-
-
-
-
-
-
- public static String firstLetterToLowerCase(String str) {
- return toLowerCase(str, 0, 1);
- }
-
-
-
-
-
-
-
-
- public static String firstLetterToUpperCase(String str) {
- return toUpperCase(str, 0, 1);
- }
-
-
-
-
-
-
-
-
- public static String MD5(String string) {
- String result = null;
- try {
- char[] charArray = string.toCharArray();
- byte[] byteArray = new byte[charArray.length];
- for (int i = 0; i < charArray.length; i++) {
- byteArray[i] = (byte) charArray[i];
- }
-
- StringBuffer hexValue = new StringBuffer();
- byte[] md5Bytes = MessageDigest.getInstance("MD5")
- .digest(byteArray);
- for (int i = 0; i < md5Bytes.length; i++) {
- int val = ((int) md5Bytes[i]) & 0xff;
- if (val < 16) {
- hexValue.append("0");
- }
- hexValue.append(Integer.toHexString(val));
- }
-
- result = hexValue.toString();
- } catch (Exception e) {
- e.printStackTrace();
- }
- return result;
- }
-
-
-
-
-
-
-
-
- public static boolean startsWithIgnoreCase(String sourceString, String newString) {
- int newLength = newString.length();
- int sourceLength = sourceString.length();
- if (newLength == sourceLength) {
- return newString.equalsIgnoreCase(sourceString);
- }
- else if (newLength < sourceLength) {
- char[] newChars = new char[newLength];
- sourceString.getChars(0, newLength, newChars, 0);
- return newString.equalsIgnoreCase(String.valueOf(newChars));
- }
- else {
- return false;
- }
- }
-
-
-
-
-
-
-
-
- public static boolean endsWithIgnoreCase(String sourceString, String newString) {
- int newLength = newString.length();
- int sourceLength = sourceString.length();
- if (newLength == sourceLength) {
- return newString.equalsIgnoreCase(sourceString);
- }
- else if (newLength < sourceLength) {
- char[] newChars = new char[newLength];
- sourceString.getChars(sourceLength - newLength, sourceLength,
- newChars, 0);
- return newString.equalsIgnoreCase(String.valueOf(newChars));
- }
- else {
- return false;
- }
- }
-
-
-
-
-
- public static String checkLength(String string, int maxLength, String appendString) {
- if (string.length() > maxLength) {
- string = string.substring(0, maxLength);
- if (appendString != null) {
- string += appendString;
- }
- }
- return string;
- }
-
-
-
-
-
- public static String checkLength(String string, int maxLength) {
- return checkLength(string, maxLength, "…");
- }
- }
|
|