栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 移动开发 > Android

实例详解Android快速开发工具类总结

Android 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

实例详解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() 
{ 
 
throw new UnsupportedOperationException("cannot be instantiated"); 
} 
public static boolean isShow = true; 
 
public static void showShort(Context context, CharSequence message) 
{ 
if (isShow) 
Toast.makeText(context, message, Toast.LENGTH_SHORT).show(); 
} 
 
public static void showShort(Context context, int message) 
{ 
if (isShow) 
Toast.makeText(context, message, Toast.LENGTH_SHORT).show(); 
} 
 
public static void showLong(Context context, CharSequence message) 
{ 
if (isShow) 
Toast.makeText(context, message, Toast.LENGTH_LONG).show(); 
} 
 
public static void showLong(Context context, int message) 
{ 
if (isShow) 
Toast.makeText(context, message, Toast.LENGTH_LONG).show(); 
} 
 
public static void show(Context context, CharSequence message, int duration) 
{ 
if (isShow) 
Toast.makeText(context, message, duration).show(); 
} 
 
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"; 
 
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); 
} 
 
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; 
} 
 
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); 
} 
 
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); 
} 
 
public static boolean contains(Context context, String key) 
{ 
SharedPreferences sp = context.getSharedPreferences(FILE_NAME, 
Context.MODE_PRIVATE); 
return sp.contains(key); 
} 
 
public static Map getAll(Context context) 
{ 
SharedPreferences sp = context.getSharedPreferences(FILE_NAME, 
Context.MODE_PRIVATE); 
return sp.getAll(); 
} 
 
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) 
{ 
} 
return null; 
} 
 
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();
}

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

public static String getString(Context context, String key) {
return getString(context, key, null);
}

public static String getString(Context context, String key, String defaultValue) {
SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
return settings.getString(key, defaultValue);
}

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

public static int getInt(Context context, String key) {
return getInt(context, key, -);
}

public static int getInt(Context context, String key, int defaultValue) {
SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
return settings.getInt(key, defaultValue);
}

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

public static long getLong(Context context, String key) {
return getLong(context, key, -);
}

public static long getLong(Context context, String key, long defaultValue) {
SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
return settings.getLong(key, defaultValue);
}

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

public static float getFloat(Context context, String key) {
return getFloat(context, key, -);
}

public static float getFloat(Context context, String key, float defaultValue) {
SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
return settings.getFloat(key, defaultValue);
}

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

public static boolean getBoolean(Context context, String key) {
return getBoolean(context, key, false);
}

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() 
{ 
 
throw new UnsupportedOperationException("cannot be instantiated"); 
} 
 
public static int dppx(Context context, float dpVal) 
{ 
return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 
dpVal, context.getResources().getDisplayMetrics()); 
} 
 
public static int sppx(Context context, float spVal) 
{ 
return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 
spVal, context.getResources().getDisplayMetrics()); 
} 
 
public static float pxdp(Context context, float pxVal) 
{ 
final float scale = context.getResources().getDisplayMetrics().density; 
return (pxVal / scale); 
} 
 
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() 
{ 
 
throw new UnsupportedOperationException("cannot be instantiated"); 
} 
 
public static boolean isSDCardEnable() 
{ 
return Environment.getExternalStorageState().equals( 
Environment.MEDIA_MOUNTED); 
} 
 
public static String getSDCardPath() 
{ 
return Environment.getExternalStorageDirectory().getAbsolutePath() 
+ File.separator; 
} 
 
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 ; 
} 
 
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; 
} 
 
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() 
{ 
 
throw new UnsupportedOperationException("cannot be instantiated"); 
} 
 
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; 
} 
 
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; 
} 
 
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; 
} 
 
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; 
} 
 
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() 
{ 
 
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; 
} 
 
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 
{ 
 
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); 
} 
 
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() 
{ 
 
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; 
} 
 
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


public class HttpUtils 
{ 
private static final int TIMEOUT_IN_MILLIONS = ; 
public interface CallBack 
{ 
void onRequestComplete(String result); 
} 
 
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(); 
} 
 
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(); 
} 
 
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", "* 
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", "*
public static String getTime(long timeInMillis, SimpleDateFormat dateFormat) {
return dateFormat.format(new Date(timeInMillis));
}

public static String getTime(long timeInMillis) {
return getTime(timeInMillis, DEFAULT_DATE_FORMAT);
}

public static long getCurrentTimeInLong() {
return System.currentTimeMillis();
}

public static String getCurrentTimeInString() {
return getTime(getCurrentTimeInLong());
}

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

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("rn");
}
fileContent.append(line);
}
return fileContent;
} catch (IOException e) {
throw new RuntimeException("IOException occurred. ", e);
} finally {
IOUtils.close(reader);
}
}

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

public static boolean writeFile(String filePath, List 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("rn");
}
fileWriter.write(line);
}
return true;
} catch (IOException e) {
throw new RuntimeException("IOException occurred. ", e);
} finally {
IOUtils.close(fileWriter);
}
}

public static boolean writeFile(String filePath, String content) {
return writeFile(filePath, content, false);
}

public static boolean writeFile(String filePath, List contentList) {
return writeFile(filePath, contentList, false);
}

public static boolean writeFile(String filePath, InputStream stream) {
return writeFile(filePath, stream, false);
}

public static boolean writeFile(String filePath, InputStream stream, boolean append) {
return writeFile(filePath != null ? new File(filePath) : null, stream, append);
}

public static boolean writeFile(File file, InputStream stream) {
return writeFile(file, stream, false);
}

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

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

public static void moveFile(File srcFile, File destFile) {
boolean rename = srcFile.renameTo(destFile);
if (!rename) {
copyFile(srcFile.getAbsolutePath(), destFile.getAbsolutePath());
deleteFile(srcFile.getAbsolutePath());
}
}

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

public static List readFileToList(String filePath, String charsetName) {
File file = new File(filePath);
List fileContent = new ArrayList();
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);
}
}

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

public static String getFileName(String filePath) {
if (StringUtils.isEmpty(filePath)) {
return filePath;
}
int filePosi = filePath.lastIndexOf(File.separator);
return (filePosi == -) ? filePath : filePath.substring(filePosi + );
}

public static String getFolderName(String filePath) {
if (StringUtils.isEmpty(filePath)) {
return filePath;
}
int filePosi = filePath.lastIndexOf(File.separator);
return (filePosi == -) ? "" : filePath.substring(, filePosi);
}

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

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

public static boolean makeFolders(String filePath) {
return makeDirs(filePath);
}

public static boolean isFileExist(String filePath) {
if (StringUtils.isBlank(filePath)) {
return false;
}
File file = new File(filePath);
return (file.exists() && file.isFile());
}

public static boolean isFolderExist(String directoryPath) {
if (StringUtils.isBlank(directoryPath)) {
return false;
}
File dire = new File(directoryPath);
return (dire.exists() && dire.isDirectory());
}

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

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

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

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

public static List geFileToListFromAssets(Context context, String fileName) {
if (context == null || StringUtils.isEmpty(fileName)) {
return null;
}
List fileContent = new ArrayList();
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;
}
}

public static List geFileToListFromRaw(Context context, int resId) {
if (context == null) {
return null;
}
List fileContent = new ArrayList();
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 {
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;
}
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/163422.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号