实例详解Android快速开发工具类总结
一、日志工具类 log.java
public class l { private l() { /* 不可被实例化 */ throw new unsupportedoperationexception("cannot be instantiated!"); } // 是否需要打印bug,可以在application的oncreate函数里面初始化 public static boolean isdebug = true; private static final string tag = "defaulttag"; // 下面四个是默认tag的函数 public static void i(string msg) { if (isdebug) log.i(tag, msg); } public static void d(string msg) { if (isdebug) log.d(tag, msg); } public static void e(string msg) { if (isdebug) log.e(tag, msg); } public static void v(string msg) { if (isdebug) log.v(tag, msg); } // 下面是传入自定义tag的函数 public static void i(string tag, string msg) { if (isdebug) log.i(tag, msg); } public static void d(string tag, string msg) { if (isdebug) log.i(tag, msg); } public static void e(string tag, string msg) { if (isdebug) log.i(tag, msg); } public static void v(string tag, string msg) { if (isdebug) log.i(tag, msg); } }
二、toast统一管理类 tost.java
public class t { private t() { /* cannot be instantiated */ throw new unsupportedoperationexception("cannot be instantiated"); } public static boolean isshow = true; /** * 短时间显示toast */ public static void showshort(context context, charsequence message) { if (isshow) toast.maketext(context, message, toast.length_short).show(); } /** * 短时间显示toast * @param message 要显示的字符串资源的id */ public static void showshort(context context, int message) { if (isshow) toast.maketext(context, message, toast.length_short).show(); } /** * 长时间显示toast */ public static void showlong(context context, charsequence message) { if (isshow) toast.maketext(context, message, toast.length_long).show(); } /** * 长时间显示toast */ public static void showlong(context context, int message) { if (isshow) toast.maketext(context, message, toast.length_long).show(); } /** * 自定义显示toast时间 */ public static void show(context context, charsequence message, int duration) { if (isshow) toast.maketext(context, message, duration).show(); } /** * 自定义显示toast时间 */ public static void show(context context, int message, int duration) { if (isshow) toast.maketext(context, message, duration).show(); } }
三、sharedpreferences封装类 sputils.java 和 preferencesutils.java
1. sputils.java
public class sputils { /** * 保存在手机里面的文件名 */ public static final string file_name = "share_data"; /** * 保存数据的方法,我们需要拿到保存数据的具体类型,然后根据类型调用不同的保存方法 * * @param context * @param key * @param object */ public static void put(context context, string key, object object) { sharedpreferences sp = context.getsharedpreferences(file_name, context.mode_private); sharedpreferences.editor editor = sp.edit(); if (object instanceof string) { editor.putstring(key, (string) object); } else if (object instanceof integer) { editor.putint(key, (integer) object); } else if (object instanceof boolean) { editor.putboolean(key, (boolean) object); } else if (object instanceof float) { editor.putfloat(key, (float) object); } else if (object instanceof long) { editor.putlong(key, (long) object); } else { editor.putstring(key, object.tostring()); } sharedpreferencescompat.apply(editor); } /** * 得到保存数据的方法,我们根据默认值得到保存的数据的具体类型,然后调用相对于的方法获取值 * * @param context * @param key * @param defaultobject * @return */ public static object get(context context, string key, object defaultobject) { sharedpreferences sp = context.getsharedpreferences(file_name, context.mode_private); 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; } /** * 移除某个key值已经对应的值 * @param context * @param key */ public static void remove(context context, string key) { sharedpreferences sp = context.getsharedpreferences(file_name, context.mode_private); sharedpreferences.editor editor = sp.edit(); editor.remove(key); sharedpreferencescompat.apply(editor); } /** * 清除所有数据 * @param context */ public static void clear(context context) { sharedpreferences sp = context.getsharedpreferences(file_name, context.mode_private); sharedpreferences.editor editor = sp.edit(); editor.clear(); sharedpreferencescompat.apply(editor); } /** * 查询某个key是否已经存在 * @param context * @param key * @return */ public static boolean contains(context context, string key) { sharedpreferences sp = context.getsharedpreferences(file_name, context.mode_private); return sp.contains(key); } /** * 返回所有的键值对 * * @param context * @return */ public static map<string, ?> getall(context context) { sharedpreferences sp = context.getsharedpreferences(file_name, context.mode_private); return sp.getall(); } /** * 创建一个解决sharedpreferencescompat.apply方法的一个兼容类 * * @author zhy * */ private static class sharedpreferencescompat { private static final method sapplymethod = findapplymethod(); /** * 反射查找apply的方法 * * @return */ @suppresswarnings({ "unchecked", "rawtypes" }) private static method findapplymethod() { try { class clz = sharedpreferences.editor.class; return clz.getmethod("apply"); } catch (nosuchmethodexception e) { } return null; } /** * 如果找到则使用apply执行,否则使用commit * * @param editor */ public static void apply(sharedpreferences.editor editor) { try { if (sapplymethod != null) { sapplymethod.invoke(editor); return; } } catch (illegalargumentexception e) { } catch (illegalaccessexception e) { } catch (invocationtargetexception e) { } editor.commit(); } } }
对sharedpreference的使用做了建议的封装,对外公布出put,get,remove,clear等等方法;
注意一点,里面所有的commit操作使用了sharedpreferencescompat.apply进行了替代,目的是尽可能的使用apply代替commit.
首先说下为什么,因为commit方法是同步的,并且我们很多时候的commit操作都是ui线程中,毕竟是io操作,尽可能异步;
所以我们使用apply进行替代,apply异步的进行写入;
但是apply相当于commit来说是new api呢,为了更好的兼容,我们做了适配;
sharedpreferencescompat也可以给大家创建兼容类提供了一定的参考
2. sputils.java
public class preferencesutils { public static string preference_name = "trineaandroidcommon"; private preferencesutils() { throw new assertionerror(); } /** * put string preferences * * @param context * @param key the name of the preference to modify * @param value the new value for the preference * @return true if the new values were successfully written to persistent storage. */ public static boolean putstring(context context, string key, string value) { sharedpreferences settings = context.getsharedpreferences(preference_name, context.mode_private); sharedpreferences.editor editor = settings.edit(); editor.putstring(key, value); return editor.commit(); } /** * get string preferences * * @param context * @param key the name of the preference to retrieve * @return the preference value if it exists, or null. throws classcastexception if there is a preference with this * name that is not a string * @see #getstring(context, string, string) */ public static string getstring(context context, string key) { return getstring(context, key, null); } /** * get string preferences * * @param context * @param key the name of the preference to retrieve * @param defaultvalue value to return if this preference does not exist * @return the preference value if it exists, or defvalue. throws classcastexception if there is a preference with * this name that is not a string */ public static string getstring(context context, string key, string defaultvalue) { sharedpreferences settings = context.getsharedpreferences(preference_name, context.mode_private); return settings.getstring(key, defaultvalue); } /** * put int preferences * * @param context * @param key the name of the preference to modify * @param value the new value for the preference * @return true if the new values were successfully written to persistent storage. */ public static boolean putint(context context, string key, int value) { sharedpreferences settings = context.getsharedpreferences(preference_name, context.mode_private); sharedpreferences.editor editor = settings.edit(); editor.putint(key, value); return editor.commit(); } /** * get int preferences * * @param context * @param key the name of the preference to retrieve * @return the preference value if it exists, or -. throws classcastexception if there is a preference with this * name that is not a int * @see #getint(context, string, int) */ public static int getint(context context, string key) { return getint(context, key, -); } /** * get int preferences * * @param context * @param key the name of the preference to retrieve * @param defaultvalue value to return if this preference does not exist * @return the preference value if it exists, or defvalue. throws classcastexception if there is a preference with * this name that is not a int */ public static int getint(context context, string key, int defaultvalue) { sharedpreferences settings = context.getsharedpreferences(preference_name, context.mode_private); return settings.getint(key, defaultvalue); } /** * put long preferences * * @param context * @param key the name of the preference to modify * @param value the new value for the preference * @return true if the new values were successfully written to persistent storage. */ public static boolean putlong(context context, string key, long value) { sharedpreferences settings = context.getsharedpreferences(preference_name, context.mode_private); sharedpreferences.editor editor = settings.edit(); editor.putlong(key, value); return editor.commit(); } /** * get long preferences * * @param context * @param key the name of the preference to retrieve * @return the preference value if it exists, or -. throws classcastexception if there is a preference with this * name that is not a long * @see #getlong(context, string, long) */ public static long getlong(context context, string key) { return getlong(context, key, -); } /** * get long preferences * * @param context * @param key the name of the preference to retrieve * @param defaultvalue value to return if this preference does not exist * @return the preference value if it exists, or defvalue. throws classcastexception if there is a preference with * this name that is not a long */ public static long getlong(context context, string key, long defaultvalue) { sharedpreferences settings = context.getsharedpreferences(preference_name, context.mode_private); return settings.getlong(key, defaultvalue); } /** * put float preferences * * @param context * @param key the name of the preference to modify * @param value the new value for the preference * @return true if the new values were successfully written to persistent storage. */ public static boolean putfloat(context context, string key, float value) { sharedpreferences settings = context.getsharedpreferences(preference_name, context.mode_private); sharedpreferences.editor editor = settings.edit(); editor.putfloat(key, value); return editor.commit(); } /** * get float preferences * * @param context * @param key the name of the preference to retrieve * @return the preference value if it exists, or -. throws classcastexception if there is a preference with this * name that is not a float * @see #getfloat(context, string, float) */ public static float getfloat(context context, string key) { return getfloat(context, key, -); } /** * get float preferences * * @param context * @param key the name of the preference to retrieve * @param defaultvalue value to return if this preference does not exist * @return the preference value if it exists, or defvalue. throws classcastexception if there is a preference with * this name that is not a float */ public static float getfloat(context context, string key, float defaultvalue) { sharedpreferences settings = context.getsharedpreferences(preference_name, context.mode_private); return settings.getfloat(key, defaultvalue); } /** * put boolean preferences * * @param context * @param key the name of the preference to modify * @param value the new value for the preference * @return true if the new values were successfully written to persistent storage. */ public static boolean putboolean(context context, string key, boolean value) { sharedpreferences settings = context.getsharedpreferences(preference_name, context.mode_private); sharedpreferences.editor editor = settings.edit(); editor.putboolean(key, value); return editor.commit(); } /** * get boolean preferences, default is false * * @param context * @param key the name of the preference to retrieve * @return the preference value if it exists, or false. throws classcastexception if there is a preference with this * name that is not a boolean * @see #getboolean(context, string, boolean) */ public static boolean getboolean(context context, string key) { return getboolean(context, key, false); } /** * get boolean preferences * * @param context * @param key the name of the preference to retrieve * @param defaultvalue value to return if this preference does not exist * @return the preference value if it exists, or defvalue. throws classcastexception if there is a preference with * this name that is not a boolean */ public static boolean getboolean(context context, string key, boolean defaultvalue) { sharedpreferences settings = context.getsharedpreferences(preference_name, context.mode_private); return settings.getboolean(key, defaultvalue); } }
四、单位转换类 densityutils.java
public class densityutils { private densityutils() { /* cannot be instantiated */ throw new unsupportedoperationexception("cannot be instantiated"); } /** * dp转px * * @param context * @param val * @return */ public static int dppx(context context, float dpval) { return (int) typedvalue.applydimension(typedvalue.complex_unit_dip, dpval, context.getresources().getdisplaymetrics()); } /** * sp转px * * @param context * @param val * @return */ public static int sppx(context context, float spval) { return (int) typedvalue.applydimension(typedvalue.complex_unit_sp, spval, context.getresources().getdisplaymetrics()); } /** * px转dp * * @param context * @param pxval * @return */ public static float pxdp(context context, float pxval) { final float scale = context.getresources().getdisplaymetrics().density; return (pxval / scale); } /** * px转sp * * @param fontscale * @param pxval * @return */ public static float pxsp(context context, float pxval) { return (pxval / context.getresources().getdisplaymetrics().scaleddensity); } }
typedvalue:
container for a dynamically typed data value. primarily used with resources for holding resource values.
applydimension(int unit, float value, displaymetrics metrics):
converts an unpacked complex data value holding a dimension to its final floating point value.
五、sd卡相关辅助类 sdcardutils.java
public class sdcardutils { private sdcardutils() { /* cannot be instantiated */ throw new unsupportedoperationexception("cannot be instantiated"); } /** * 判断sdcard是否可用 * * @return */ public static boolean issdcardenable() { return environment.getexternalstoragestate().equals( environment.media_mounted); } /** * 获取sd卡路径 * * @return */ public static string getsdcardpath() { return environment.getexternalstoragedirectory().getabsolutepath() + file.separator; } /** * 获取sd卡的剩余容量 单位byte * * @return */ public static long getsdcardallsize() { if (issdcardenable()) { statfs stat = new statfs(getsdcardpath()); // 获取空闲的数据块的数量 long availableblocks = (long) stat.getavailableblocks() - ; // 获取单个数据块的大小(byte) long freeblocks = stat.getavailableblocks(); return freeblocks * availableblocks; } return ; } /** * 获取指定路径所在空间的剩余可用容量字节数,单位byte * * @param filepath * @return 容量字节 sdcard可用空间,内部存储可用空间 */ public static long getfreebytes(string filepath) { // 如果是sd卡的下的路径,则获取sd卡可用容量 if (filepath.startswith(getsdcardpath())) { filepath = getsdcardpath(); } else {// 如果是内部存储的路径,则获取内存存储的可用容量 filepath = environment.getdatadirectory().getabsolutepath(); } statfs stat = new statfs(filepath); long availableblocks = (long) stat.getavailableblocks() - ; return stat.getblocksize() * availableblocks; } /** * 获取系统存储路径 * * @return */ public static string getrootdirectorypath() { return environment.getrootdirectory().getabsolutepath(); } }
statfs 是android提供的一个类:
retrieve overall information about the space on a filesystem. this is a wrapper for unix statvfs().
检索一个文件系统的整体信息空间。这是一个unix statvfs() 包装器
六、屏幕相关辅助类 screenutils.java
public class screenutils { private screenutils() { /* cannot be instantiated */ throw new unsupportedoperationexception("cannot be instantiated"); } /** * 获得屏幕高度 * * @param context * @return */ public static int getscreenwidth(context context) { windowmanager wm = (windowmanager) context .getsystemservice(context.window_service); displaymetrics outmetrics = new displaymetrics(); wm.getdefaultdisplay().getmetrics(outmetrics); return outmetrics.widthpixels; } /** * 获得屏幕宽度 * * @param context * @return */ public static int getscreenheight(context context) { windowmanager wm = (windowmanager) context .getsystemservice(context.window_service); displaymetrics outmetrics = new displaymetrics(); wm.getdefaultdisplay().getmetrics(outmetrics); return outmetrics.heightpixels; } /** * 获得状态栏的高度 * * @param context * @return */ public static int getstatusheight(context context) { int statusheight = -; 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; } /** * 获取当前屏幕截图,包含状态栏 * * @param activity * @return */ public static bitmap snapshotwithstatusbar(activity activity) { view view = activity.getwindow().getdecorview(); view.setdrawingcacheenabled(true); view.builddrawingcache(); bitmap bmp = view.getdrawingcache(); int width = getscreenwidth(activity); int height = getscreenheight(activity); bitmap bp = null; bp = bitmap.createbitmap(bmp, , , width, height); view.destroydrawingcache(); return bp; } /** * 获取当前屏幕截图,不包含状态栏 * * @param activity * @return */ public static bitmap snapshotwithoutstatusbar(activity activity) { view view = activity.getwindow().getdecorview(); view.setdrawingcacheenabled(true); view.builddrawingcache(); bitmap bmp = view.getdrawingcache(); rect frame = new rect(); activity.getwindow().getdecorview().getwindowvisibledisplayframe(frame); int statusbarheight = frame.top; int width = getscreenwidth(activity); int height = getscreenheight(activity); bitmap bp = null; bp = bitmap.createbitmap(bmp, , statusbarheight, width, height - statusbarheight); view.destroydrawingcache(); return bp; } }
七、app相关辅助类 apputils.java
public class apputils { private apputils() { /* cannot be instantiated */ throw new unsupportedoperationexception("cannot be instantiated"); } /** * 获取应用程序名称 */ public static string getappname(context context) { try { packagemanager packagemanager = context.getpackagemanager(); packageinfo packageinfo = packagemanager.getpackageinfo( context.getpackagename(), ); int labelres = packageinfo.applicationinfo.labelres; return context.getresources().getstring(labelres); } catch (namenotfoundexception e) { e.printstacktrace(); } return null; } /** * [获取应用程序版本名称信息] * * @param context * @return 当前应用的版本名称 */ public static string getversionname(context context) { try { packagemanager packagemanager = context.getpackagemanager(); packageinfo packageinfo = packagemanager.getpackageinfo( context.getpackagename(), ); return packageinfo.versionname; } catch (namenotfoundexception e) { e.printstacktrace(); } return null; } }
八、软键盘相关辅助类keyboardutils.java
/** * 打开或关闭软键盘 */ public class keyboardutils { /** * 打卡软键盘 * * @param medittext 输入框 * @param mcontext 上下文 */ public static void openkeybord(edittext medittext, context mcontext) { inputmethodmanager imm = (inputmethodmanager) mcontext .getsystemservice(context.input_method_service); imm.showsoftinput(medittext, inputmethodmanager.result_shown); imm.togglesoftinput(inputmethodmanager.show_forced, inputmethodmanager.hide_implicit_only); } /** * 关闭软键盘 * * @param medittext 输入框 * @param mcontext 上下文 */ public static void closekeybord(edittext medittext, context mcontext) { inputmethodmanager imm = (inputmethodmanager) mcontext .getsystemservice(context.input_method_service); imm.hidesoftinputfromwindow(medittext.getwindowtoken(), ); } }
九、网络相关辅助类 netutils.java
public class netutils { private netutils() { /* cannot be instantiated */ throw new unsupportedoperationexception("cannot be instantiated"); } /** * 判断网络是否连接 */ public static boolean isconnected(context context) { connectivitymanager connectivity = (connectivitymanager) context .getsystemservice(context.connectivity_service); if (null != connectivity) { networkinfo info = connectivity.getactivenetworkinfo(); if (null != info && info.isconnected()) { if (info.getstate() == networkinfo.state.connected) { return true; } } } return false; } /** * 判断是否是wifi连接 */ public static boolean iswifi(context context) { connectivitymanager cm = (connectivitymanager) context .getsystemservice(context.connectivity_service); if (cm == null) return false; return cm.getactivenetworkinfo().gettype() == connectivitymanager.type_wifi; } /** * 打开网络设置界面 */ public static void opensetting(activity activity) { intent intent = new intent("/"); componentname cm = new componentname("com.android.settings", "com.android.settings.wirelesssettings"); intent.setcomponent(cm); intent.setaction("android.intent.action.view"); activity.startactivityforresult(intent, ); } }
十、http相关辅助类 httputils.java
/** * http请求的工具类 */ public class httputils { private static final int timeout_in_millions = ; public interface callback { void onrequestcomplete(string result); } /** * 异步的get请求 * * @param urlstr * @param callback */ public static void dogetasyn(final string urlstr, final callback callback) { new thread() { public void run() { try { string result = doget(urlstr); if (callback != null) { callback.onrequestcomplete(result); } } catch (exception e) { e.printstacktrace(); } }; }.start(); } /** * 异步的post请求 * @param urlstr * @param params * @param callback * @throws exception */ public static void dopostasyn(final string urlstr, final string params, final callback callback) throws exception { new thread() { public void run() { try { string result = dopost(urlstr, params); if (callback != null) { callback.onrequestcomplete(result); } } catch (exception e) { e.printstacktrace(); } }; }.start(); } /** * get请求,获得返回数据 * * @param urlstr * @return * @throws exception */ 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() == ) { is = conn.getinputstream(); baos = new bytearrayoutputstream(); int len = -; byte[] buf = new byte[]; while ((len = is.read(buf)) != -) { baos.write(buf, , len); } baos.flush(); return baos.tostring(); } else { throw new runtimeexception(" responsecode is not ... "); } } catch (exception e) { e.printstacktrace(); } finally { try { if (is != null) is.close(); } catch (ioexception e) { } try { if (baos != null) baos.close(); } catch (ioexception e) { } conn.disconnect(); } return null ; } /** * 向指定 url 发送post方法的请求 * * @param url * 发送请求的 url * @param param * 请求参数,请求参数应该是 name=value&name=value 的形式。 * @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); // 打开和url之间的连接 httpurlconnection conn = (httpurlconnection) realurl .openconnection(); // 设置通用的请求属性 conn.setrequestproperty("accept", "*/*"); conn.setrequestproperty("connection", "keep-alive"); conn.setrequestmethod("post"); conn.setrequestproperty("content-type", "application/x-www-form-urlencoded"); conn.setrequestproperty("charset", "utf-"); conn.setusecaches(false); // 发送post请求必须设置如下两行 conn.setdooutput(true); conn.setdoinput(true); conn.setreadtimeout(timeout_in_millions); conn.setconnecttimeout(timeout_in_millions); if (param != null && !param.trim().equals("")) { // 获取urlconnection对象对应的输出流 out = new printwriter(conn.getoutputstream()); // 发送请求参数 out.print(param); // flush输出流的缓冲 out.flush(); } // 定义bufferedreader输入流来读取url的响应 in = new bufferedreader( new inputstreamreader(conn.getinputstream())); string line; while ((line = in.readline()) != null) { result += line; } } catch (exception e) { e.printstacktrace(); } // 使用finally块来关闭输出流、输入流 finally { try { if (out != null) { out.close(); } if (in != null) { in.close(); } } catch (ioexception ex) { ex.printstacktrace(); } } return result; } }
十一、时间工具类 timeutils.java
public class timeutils { public static final simpledateformat default_date_format = new simpledateformat("yyyy-mm-dd hh:mm:ss"); public static final simpledateformat date_format_date = new simpledateformat("yyyy-mm-dd"); private timeutils() { throw new assertionerror(); } /** * long time to string * * @param timeinmillis * @param dateformat * @return */ public static string gettime(long timeinmillis, simpledateformat dateformat) { return dateformat.format(new date(timeinmillis)); } /** * long time to string, format is {@link #default_date_format} * * @param timeinmillis * @return */ public static string gettime(long timeinmillis) { return gettime(timeinmillis, default_date_format); } /** * get current time in milliseconds * * @return */ public static long getcurrenttimeinlong() { return system.currenttimemillis(); } /** * get current time in milliseconds, format is {@link #default_date_format} * * @return */ public static string getcurrenttimeinstring() { return gettime(getcurrenttimeinlong()); } /** * get current time in milliseconds * * @return */ public static string getcurrenttimeinstring(simpledateformat dateformat) { return gettime(getcurrenttimeinlong(), dateformat); } }
十二、文件工具类 fileutils.java
public class fileutils { public final static string file_extension_separator = "."; private fileutils() { throw new assertionerror(); } /** * read file * * @param filepath * @param charsetname the name of a supported {@link java.nio.charset.charset </code>charset<code>} * @return if file not exist, return null, else return content of file * @throws runtimeexception if an error occurs while operator bufferedreader */ public static stringbuilder readfile(string filepath, string charsetname) { file file = new file(filepath); stringbuilder filecontent = new stringbuilder(""); if (file == null || !file.isfile()) { return null; } bufferedreader reader = null; try { inputstreamreader is = new inputstreamreader(new fileinputstream(file), charsetname); reader = new bufferedreader(is); string line = null; while ((line = reader.readline()) != null) { if (!filecontent.tostring().equals("")) { filecontent.append("\r\n"); } filecontent.append(line); } return filecontent; } catch (ioexception e) { throw new runtimeexception("ioexception occurred. ", e); } finally { ioutils.close(reader); } } /** * write file * * @param filepath * @param content * @param append is append, if true, write to the end of file, else clear content of file and write into it * @return return false if content is empty, true otherwise * @throws runtimeexception if an error occurs while operator filewriter */ public static boolean writefile(string filepath, string content, boolean append) { if (stringutils.isempty(content)) { return false; } filewriter filewriter = null; try { makedirs(filepath); filewriter = new filewriter(filepath, append); filewriter.write(content); return true; } catch (ioexception e) { throw new runtimeexception("ioexception occurred. ", e); } finally { ioutils.close(filewriter); } } /** * write file * * @param filepath * @param contentlist * @param append is append, if true, write to the end of file, else clear content of file and write into it * @return return false if contentlist is empty, true otherwise * @throws runtimeexception if an error occurs while operator filewriter */ public static boolean writefile(string filepath, list<string> contentlist, boolean append) { if (listutils.isempty(contentlist)) { return false; } filewriter filewriter = null; try { makedirs(filepath); filewriter = new filewriter(filepath, append); int i = ; for (string line : contentlist) { if (i++ > ) { filewriter.write("\r\n"); } filewriter.write(line); } return true; } catch (ioexception e) { throw new runtimeexception("ioexception occurred. ", e); } finally { ioutils.close(filewriter); } } /** * write file, the string will be written to the begin of the file * * @param filepath * @param content * @return */ public static boolean writefile(string filepath, string content) { return writefile(filepath, content, false); } /** * write file, the string list will be written to the begin of the file * * @param filepath * @param contentlist * @return */ public static boolean writefile(string filepath, list<string> contentlist) { return writefile(filepath, contentlist, false); } /** * write file, the bytes will be written to the begin of the file * * @param filepath * @param stream * @return * @see {@link #writefile(string, inputstream, boolean)} */ public static boolean writefile(string filepath, inputstream stream) { return writefile(filepath, stream, false); } /** * write file * * @param file the file to be opened for writing. * @param stream the input stream * @param append if <code>true</code>, then bytes will be written to the end of the file rather than the beginning * @return return true * @throws runtimeexception if an error occurs while operator fileoutputstream */ public static boolean writefile(string filepath, inputstream stream, boolean append) { return writefile(filepath != null ? new file(filepath) : null, stream, append); } /** * write file, the bytes will be written to the begin of the file * * @param file * @param stream * @return * @see {@link #writefile(file, inputstream, boolean)} */ public static boolean writefile(file file, inputstream stream) { return writefile(file, stream, false); } /** * write file * * @param file the file to be opened for writing. * @param stream the input stream * @param append if <code>true</code>, then bytes will be written to the end of the file rather than the beginning * @return return true * @throws runtimeexception if an error occurs while operator fileoutputstream */ public static boolean writefile(file file, inputstream stream, boolean append) { outputstream o = null; try { makedirs(file.getabsolutepath()); o = new fileoutputstream(file, append); byte data[] = new byte[]; int length = -; while ((length = stream.read(data)) != -) { o.write(data, , length); } o.flush(); return true; } catch (filenotfoundexception e) { throw new runtimeexception("filenotfoundexception occurred. ", e); } catch (ioexception e) { throw new runtimeexception("ioexception occurred. ", e); } finally { ioutils.close(o); ioutils.close(stream); } } /** * move file * * @param sourcefilepath * @param destfilepath */ public static void movefile(string sourcefilepath, string destfilepath) { if (textutils.isempty(sourcefilepath) || textutils.isempty(destfilepath)) { throw new runtimeexception("both sourcefilepath and destfilepath cannot be null."); } movefile(new file(sourcefilepath), new file(destfilepath)); } /** * move file * * @param srcfile * @param destfile */ public static void movefile(file srcfile, file destfile) { boolean rename = srcfile.renameto(destfile); if (!rename) { copyfile(srcfile.getabsolutepath(), destfile.getabsolutepath()); deletefile(srcfile.getabsolutepath()); } } /** * copy file * * @param sourcefilepath * @param destfilepath * @return * @throws runtimeexception if an error occurs while operator fileoutputstream */ public static boolean copyfile(string sourcefilepath, string destfilepath) { inputstream inputstream = null; try { inputstream = new fileinputstream(sourcefilepath); } catch (filenotfoundexception e) { throw new runtimeexception("filenotfoundexception occurred. ", e); } return writefile(destfilepath, inputstream); } /** * read file to string list, a element of list is a line * * @param filepath * @param charsetname the name of a supported {@link java.nio.charset.charset </code>charset<code>} * @return if file not exist, return null, else return content of file * @throws runtimeexception if an error occurs while operator bufferedreader */ public static list<string> readfiletolist(string filepath, string charsetname) { file file = new file(filepath); list<string> filecontent = new arraylist<string>(); if (file == null || !file.isfile()) { return null; } bufferedreader reader = null; try { inputstreamreader is = new inputstreamreader(new fileinputstream(file), charsetname); reader = new bufferedreader(is); string line = null; while ((line = reader.readline()) != null) { filecontent.add(line); } return filecontent; } catch (ioexception e) { throw new runtimeexception("ioexception occurred. ", e); } finally { ioutils.close(reader); } } /** * get file name from path, not include suffix * * <pre> * getfilenamewithoutextension(null) = null * getfilenamewithoutextension("") = "" * getfilenamewithoutextension(" ") = " " * getfilenamewithoutextension("abc") = "abc" * getfilenamewithoutextension("a.mp") = "a" * getfilenamewithoutextension("a.b.rmvb") = "a.b" * getfilenamewithoutextension("c:\\") = "" * getfilenamewithoutextension("c:\\a") = "a" * getfilenamewithoutextension("c:\\a.b") = "a" * getfilenamewithoutextension("c:a.txt\\a") = "a" * getfilenamewithoutextension("/home/admin") = "admin" * getfilenamewithoutextension("/home/admin/a.txt/b.mp") = "b" * </pre> * * @param filepath * @return file name from path, not include suffix * @see */ public static string getfilenamewithoutextension(string filepath) { if (stringutils.isempty(filepath)) { return filepath; } int extenposi = filepath.lastindexof(file_extension_separator); int fileposi = filepath.lastindexof(file.separator); if (fileposi == -) { return (extenposi == - ? filepath : filepath.substring(, extenposi)); } if (extenposi == -) { return filepath.substring(fileposi + ); } return (fileposi < extenposi ? filepath.substring(fileposi + , extenposi) : filepath.substring(fileposi + )); } /** * get file name from path, include suffix * * <pre> * getfilename(null) = null * getfilename("") = "" * getfilename(" ") = " " * getfilename("a.mp") = "a.mp" * getfilename("a.b.rmvb") = "a.b.rmvb" * getfilename("abc") = "abc" * getfilename("c:\\") = "" * getfilename("c:\\a") = "a" * getfilename("c:\\a.b") = "a.b" * getfilename("c:a.txt\\a") = "a" * getfilename("/home/admin") = "admin" * getfilename("/home/admin/a.txt/b.mp") = "b.mp" * </pre> * * @param filepath * @return file name from path, include suffix */ public static string getfilename(string filepath) { if (stringutils.isempty(filepath)) { return filepath; } int fileposi = filepath.lastindexof(file.separator); return (fileposi == -) ? filepath : filepath.substring(fileposi + ); } /** * get folder name from path * * <pre> * getfoldername(null) = null * getfoldername("") = "" * getfoldername(" ") = "" * getfoldername("a.mp") = "" * getfoldername("a.b.rmvb") = "" * getfoldername("abc") = "" * getfoldername("c:\\") = "c:" * getfoldername("c:\\a") = "c:" * getfoldername("c:\\a.b") = "c:" * getfoldername("c:a.txt\\a") = "c:a.txt" * getfoldername("c:a\\b\\c\\d.txt") = "c:a\\b\\c" * getfoldername("/home/admin") = "/home" * getfoldername("/home/admin/a.txt/b.mp") = "/home/admin/a.txt" * </pre> * * @param filepath * @return */ public static string getfoldername(string filepath) { if (stringutils.isempty(filepath)) { return filepath; } int fileposi = filepath.lastindexof(file.separator); return (fileposi == -) ? "" : filepath.substring(, fileposi); } /** * get suffix of file from path * * <pre> * getfileextension(null) = "" * getfileextension("") = "" * getfileextension(" ") = " " * getfileextension("a.mp") = "mp" * getfileextension("a.b.rmvb") = "rmvb" * getfileextension("abc") = "" * getfileextension("c:\\") = "" * getfileextension("c:\\a") = "" * getfileextension("c:\\a.b") = "b" * getfileextension("c:a.txt\\a") = "" * getfileextension("/home/admin") = "" * getfileextension("/home/admin/a.txt/b") = "" * getfileextension("/home/admin/a.txt/b.mp") = "mp" * </pre> * * @param filepath * @return */ public static string getfileextension(string filepath) { if (stringutils.isblank(filepath)) { return filepath; } int extenposi = filepath.lastindexof(file_extension_separator); int fileposi = filepath.lastindexof(file.separator); if (extenposi == -) { return ""; } return (fileposi >= extenposi) ? "" : filepath.substring(extenposi + ); } /** * creates the directory named by the trailing filename of this file, including the complete directory path required * to create this directory. <br/> * <br/> * <ul> * <strong>attentions:</strong> * <li>makedirs("c:\\users\\trinea") can only create users folder</li> * <li>makefolder("c:\\users\\trinea\\") can create trinea folder</li> * </ul> * * @param filepath * @return true if the necessary directories have been created or the target directory already exists, false one of * the directories can not be created. * <ul> * <li>if {@link fileutils#getfoldername(string)} return null, return false</li> * <li>if target directory already exists, return true</li> * <li>return {@link java.io.file#makefolder}</li> * </ul> */ public static boolean makedirs(string filepath) { string foldername = getfoldername(filepath); if (stringutils.isempty(foldername)) { return false; } file folder = new file(foldername); return (folder.exists() && folder.isdirectory()) ? true : folder.mkdirs(); } /** * @param filepath * @return * @see #makedirs(string) */ public static boolean makefolders(string filepath) { return makedirs(filepath); } /** * indicates if this file represents a file on the underlying file system. * * @param filepath * @return */ public static boolean isfileexist(string filepath) { if (stringutils.isblank(filepath)) { return false; } file file = new file(filepath); return (file.exists() && file.isfile()); } /** * indicates if this file represents a directory on the underlying file system. * * @param directorypath * @return */ public static boolean isfolderexist(string directorypath) { if (stringutils.isblank(directorypath)) { return false; } file dire = new file(directorypath); return (dire.exists() && dire.isdirectory()); } /** * delete file or directory * <ul> * <li>if path is null or empty, return true</li> * <li>if path not exist, return true</li> * <li>if path exist, delete recursion. return true</li> * <ul> * * @param path * @return */ public static boolean deletefile(string path) { if (stringutils.isblank(path)) { return true; } file file = new file(path); if (!file.exists()) { return true; } if (file.isfile()) { return file.delete(); } if (!file.isdirectory()) { return false; } for (file f : file.listfiles()) { if (f.isfile()) { f.delete(); } else if (f.isdirectory()) { deletefile(f.getabsolutepath()); } } return file.delete(); } /** * get file size * <ul> * <li>if path is null or empty, return -</li> * <li>if path exist and it is a file, return file size, else return -</li> * <ul> * * @param path * @return returns the length of this file in bytes. returns - if the file does not exist. */ public static long getfilesize(string path) { if (stringutils.isblank(path)) { return -; } file file = new file(path); return (file.exists() && file.isfile() ? file.length() : -); } }
十三、assets和raw资源工具类 resourceutils.java
public class resourceutils { private resourceutils() { throw new assertionerror(); } /** * get an asset using access_streaming mode. this provides access to files that have been bundled with an * application as assets -- that is, files placed in to the "assets" directory. * * @param context * @param filename the name of the asset to open. this name can be hierarchical. * @return */ public static string gefilefromassets(context context, string filename) { if (context == null || stringutils.isempty(filename)) { return null; } stringbuilder s = new stringbuilder(""); try { inputstreamreader in = new inputstreamreader(context.getresources().getassets().open(filename)); bufferedreader br = new bufferedreader(in); string line; while ((line = br.readline()) != null) { s.append(line); } return s.tostring(); } catch (ioexception e) { e.printstacktrace(); return null; } } /** * get content from a raw resource. this can only be used with resources whose value is the name of an asset files * -- that is, it can be used to open drawable, sound, and raw resources; it will fail on string and color * resources. * * @param context * @param resid the resource identifier to open, as generated by the appt tool. * @return */ public static string gefilefromraw(context context, int resid) { if (context == null) { return null; } stringbuilder s = new stringbuilder(); try { inputstreamreader in = new inputstreamreader(context.getresources().openrawresource(resid)); bufferedreader br = new bufferedreader(in); string line; while ((line = br.readline()) != null) { s.append(line); } return s.tostring(); } catch (ioexception e) { e.printstacktrace(); return null; } } /** * same to {@link resourceutils#gefilefromassets(context, string)}, but return type is list<string> * * @param context * @param filename * @return */ public static list<string> gefiletolistfromassets(context context, string filename) { if (context == null || stringutils.isempty(filename)) { return null; } list<string> filecontent = new arraylist<string>(); try { inputstreamreader in = new inputstreamreader(context.getresources().getassets().open(filename)); bufferedreader br = new bufferedreader(in); string line; while ((line = br.readline()) != null) { filecontent.add(line); } br.close(); return filecontent; } catch (ioexception e) { e.printstacktrace(); return null; } } /** * same to {@link resourceutils#gefilefromraw(context, int)}, but return type is list<string> * * @param context * @param resid * @return */ public static list<string> gefiletolistfromraw(context context, int resid) { if (context == null) { return null; } list<string> filecontent = new arraylist<string>(); bufferedreader reader = null; try { inputstreamreader in = new inputstreamreader(context.getresources().openrawresource(resid)); reader = new bufferedreader(in); string line = null; while ((line = reader.readline()) != null) { filecontent.add(line); } reader.close(); return filecontent; } catch (ioexception e) { e.printstacktrace(); return null; } } }
十四、单例工具类 singletonutils.java
public abstract class singletonutils<t> { private t instance; protected abstract t newinstance(); public final t getinstance() { if (instance == null) { synchronized (singletonutils.class) { if (instance == null) { instance = newinstance(); } } } return instance; } }
十五、数据库工具类 sqliteutils.java
public class sqliteutils { private static volatile sqliteutils instance; private dbhelper dbhelper; private sqlitedatabase db; private sqliteutils(context context) { dbhelper = new dbhelper(context); db = dbhelper.getwritabledatabase(); } public static sqliteutils getinstance(context context) { if (instance == null) { synchronized (sqliteutils.class) { if (instance == null) { instance = new sqliteutils(context); } } } return instance; } public sqlitedatabase getdb() { return db; } }