参考:
https://blog.csdn.net/lmj623565791/article/details/38965311
一.SharedPreferences封装类SPUtils
package com.zhy.utils;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Map;
import android.content.Context;
import android.content.SharedPreferences;
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也可以给大家创建兼容类提供了一定的参考~~
二.单位转换类 DensityUtils
package com.zhy.utils;
import android.content.Context;
import android.util.TypedValue;
/**
* 常用单位转换的辅助类
*
*
*
*/
public class DensityUtils
{
private DensityUtils()
{
/* cannot be instantiated */
throw new UnsupportedOperationException("cannot be instantiated");
}
/**
* dp转px
*
* @param context
* @param val
* @return
*/
public static int dp2px(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 sp2px(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 px2dp(Context context, float pxVal)
{
final float scale = context.getResources().getDisplayMetrics().density;
return (pxVal / scale);
}
/**
* px转sp
*
* @param fontScale
* @param pxVal
* @return
*/
public static float px2sp(Context context, float pxVal)
{
return (pxVal / context.getResources().getDisplayMetrics().scaledDensity);
}
}
三、SD卡相关辅助类 SDCardUtils
package com.zhy.utils;
import java.io.File;
import android.os.Environment;
import android.os.StatFs;
/**
* SD卡相关的辅助类
*
*
*
*/
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() - 4;
// 获取单个数据块的大小(byte)
long freeBlocks = stat.getAvailableBlocks();
return freeBlocks * availableBlocks;
}
return 0;
}
/**
* 获取指定路径所在空间的剩余可用容量字节数,单位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() - 4;
return stat.getBlockSize() * availableBlocks;
}
/**
* 获取系统存储路径
*
* @return
*/
public static String getRootDirectoryPath()
{
return Environment.getRootDirectory().getAbsolutePath();
}
}
四、屏幕相关辅助类 ScreenUtils
package com.zhy.utils;
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 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 = -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;
}
/**
* 获取当前屏幕截图,包含状态栏
*
* @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, 0, 0, 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, 0, statusBarHeight, width, height
- statusBarHeight);
view.destroyDrawingCache();
return bp;
}
}
五、App相关辅助类
package com.zhy.utils;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
/**
* 跟App相关的辅助类
*
*
*
*/
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(), 0);
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(), 0);
return packageInfo.versionName;
} catch (NameNotFoundException e)
{
e.printStackTrace();
}
return null;
}
}
六、软键盘相关辅助类KeyBoardUtils
package com.zhy.utils;
import android.content.Context;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
/**
* 打开或关闭软键盘
*
* @author zhy
*
*/
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(), 0);
}
}
七、网络相关辅助类 NetUtils
package com.zhy.utils;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
/**
* 跟网络相关的工具类
*
*
*
*/
public class NetUtils
{
private NetUtils()
{
/* cannot be instantiated */
throw new UnsupportedOperationException("cannot be instantiated");
}
/**
* 判断网络是否连接
*
* @param context
* @return
*/
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, 0);
}
}
八、Http相关辅助类 HttpUtils
package com.zhy.utils;
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.URL;
/**
* Http请求的工具类
*
* @author zhy
*
*/
public class HttpUtils
{
private static final int TIMEOUT_IN_MILLIONS = 5000;
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() == 200)
{
is = conn.getInputStream();
baos = new ByteArrayOutputStream();
int len = -1;
byte[] buf = new byte[128];
while ((len = is.read(buf)) != -1)
{
baos.write(buf, 0, len);
}
baos.flush();
return baos.toString();
} else
{
throw new RuntimeException(" responseCode is not 200 ... ");
}
} 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
* 请求参数,请求参数应该是 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);
// 打开和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-8");
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;
}
}
九、文件管理工具类
import com.orhanobut.logger.Logger;
import org.greenrobot.greendao.annotation.NotNull;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.util.Locale;
/**
* Author:DoctorWei
* Time:2018/12/10 15:51
* Description:文件管理工具类 包括文件的复制进度回调 打开 和遍历
* email:1348172474@qq.com
*/
public class FileUtil {
/**
* 文件的复制
*/
public static void copyFile(String parentDir, String fileName, File originFile, CopyListener copyListener) {
try {
FileInputStream fileInputStream = new FileInputStream(originFile);
copyFile(parentDir, fileName, fileInputStream, originFile.length(), copyListener);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
/**
* 文件的复制
*/
public static void copyFile(String parentDir, String fileName, InputStream inputStream, long totalLenth, CopyListener copyListener) {
try {
copyListener.startCopy();
File newFile = new File(parentDir + File.separator + fileName);
FileOutputStream fileOutputStream = new FileOutputStream(newFile);
byte[] data = new byte[2048];
int len = 0;
long currentLenght = 0;
while ((len = inputStream.read(data)) != -1) {
fileOutputStream.write(data, 0, len);
currentLenght += len;
copyListener.progress((int) (currentLenght * 100 / totalLenth));
}
copyListener.finish(newFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public interface CopyListener {
void startCopy();
void progress(int progress);
void finish(File file);
}
/**
* 创建文件
*
* @param path 文件所在目录的目录名,如/java/test/0.txt,要在当前目录下创建一个文件名为1.txt的文件,<br>
* 则path为/java/test,fileName为1.txt
* @param fileName 文件名
* @return 文件新建成功则返回true
*/
public static boolean createFile(@NotNull String path,@NotNull String fileName) {
File file = new File(path + File.separator + fileName);
if (file.exists()) {
Logger.w("新建文件失败:file.exist()=" + file.exists());
return false;
} else {
try {
boolean isCreated = file.createNewFile();
return isCreated;
} catch (IOException e) {
e.printStackTrace();
}
}
return false;
}
/**
* 删除单个文件
*
* @param path 文件所在路径名
* @param fileName 文件名
* @return 删除成功则返回true
*/
public static boolean deleteFile(@NotNull String path, @NotNull String fileName) {
File file = new File(path + File.separator + fileName);
if (file.exists()) {
boolean isDeleted = file.delete();
return isDeleted;
} else {
return false;
}
}
/**
* 根据文件名获得文件的扩展名
*
* @param fileName 文件名
* @return 文件扩展名(不带点)
*/
public static String getFileSuffix(@NotNull String fileName) {
int index = fileName.lastIndexOf(".");
String suffix = fileName.substring(index + 1, fileName.length());
return suffix;
}
/**
* 重命名文件
*
* @param oldPath 旧文件的绝对路径
* @param newPath 新文件的绝对路径
* @return 文件重命名成功则返回true
*/
public static boolean renameTo(@NotNull String oldPath, @NotNull String newPath) {
if (oldPath.equals(newPath)) {
Logger.w( "文件重命名失败:新旧文件名绝对路径相同!");
return false;
}
File oldFile = new File(oldPath);
File newFile = new File(newPath);
boolean isSuccess = oldFile.renameTo(newFile);
Logger.w("文件重命名是否成功:" + isSuccess);
return isSuccess;
}
/**
* 重命名文件
*
* @param oldFile 旧文件对象
* @param newFile 新文件对象
* @return 文件重命名成功则返回true
*/
public static boolean renameTo(File oldFile, File newFile) {
if (oldFile.equals(newFile)) {
Logger.w( "文件重命名失败:旧文件对象和新文件对象相同!");
return false;
}
boolean isSuccess = oldFile.renameTo(newFile);
Logger.w("文件重命名是否成功:" + isSuccess);
return isSuccess;
}
/**
* 重命名文件
*
* @param oldFile 旧文件对象,File类型
* @param newName 新文件的文件名,String类型
* @return 重命名成功则返回true
*/
public static boolean renameTo(File oldFile, String newName) {
File newFile = new File(oldFile.getParentFile() + File.separator + newName);
boolean flag = oldFile.renameTo(newFile);
return flag;
}
/**
* 文件大小的格式化
*
* @param size 文件大小,单位为byte
* @return 文件大小格式化后的文本
*/
public static String formatSize(long size) {
DecimalFormat df = new DecimalFormat("####.00");
if (size < 1024) // 小于1KB
{
return size + "Byte";
} else if (size < 1024 * 1024) // 小于1MB
{
float kSize = size / 1024f;
return df.format(kSize) + "KB";
} else if (size < 1024 * 1024 * 1024) // 小于1GB
{
float mSize = size / 1024f / 1024f;
return df.format(mSize) + "MB";
} else if (size < 1024L * 1024L * 1024L * 1024L) // 小于1TB
{
float gSize = size / 1024f / 1024f / 1024f;
return df.format(gSize) + "GB";
} else {
return "size: error";
}
}
/**
* 获取某个路径下的文件列表
*
* @param path 文件路径
* @return 文件列表File[] files
*/
public static File[] getFileList(String path) {
File file = new File(path);
if (file.isDirectory()) {
File[] files = file.listFiles();
if (files != null) {
return files;
} else {
return null;
}
} else {
return null;
}
}
/**
* 获取某个目录下的文件列表
*
* @param directory 目录
* @return 文件列表File[] files
*/
public static File[] getFileList(File directory) {
File[] files = directory.listFiles();
if (files != null) {
return files;
} else {
return null;
}
}
/** 取得文件或文件夹大小 */
public static long getFileSize(File file) {
long size = 0;
if (!file.isDirectory()) { // 文件
return file.length();
}
File files[] = file.listFiles(); // 文件夹(递归)
for (int i = 0; i < files.length; i++) {
if (files[i].isDirectory()) {
size = size + getFileSize(files[i]);
} else {
size = size + files[i].length();
}
}
return size;
}
/** 删除文件 **/
public void deleteFile(File f) {
if (f.isDirectory()) {
File[] files = f.listFiles();
if (files != null && files.length > 0) {
for (int i = 0; i < files.length; ++i) {
deleteFile(files[i]);
}
}
}
f.delete();
}
}
android中用到的文件管理类
package com.cgw.module_base.utils;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.support.v4.content.FileProvider;
import android.widget.Toast;
import com.cgw.module_base.base.BaseApplication;
import com.cgw.module_base.base.BaseConfig;
import com.cgw.msg.utils.DateUtils;
import com.socks.library.KLog;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
/**
* 文件操作工具类
* dongdd on 2017/8/27 21:57
*/
public class FileUtils {
public static final String ICON_DIR = "icon";
public static final String APP_STORAGE_ROOT = "CGW301CDM";
/**
* 获取默认的文件路径 SD卡优先
*
* @return
*/
public static String getFileDefaultPath() {
String filePath;
// 判断是否存在SD卡
boolean hasSDCard = Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
// SD卡根目录的
if (hasSDCard) {
filePath = Environment.getExternalStorageDirectory().getAbsolutePath();
} else {// 系统下载缓存根目录的
filePath = Environment.getDownloadCacheDirectory().getAbsolutePath();
}
KLog.d(BaseConfig.LOG, "文件默认路径:" + filePath);
return filePath;
}
/**
* 获取默认的文件路径 SD卡优先
*
* @return
*/
public static String getFileDefaultPath(String fileName) {
String filePath;
// 判断是否存在SD卡
boolean hasSDCard = Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
// SD卡根目录的
if (hasSDCard) {
filePath = Environment.getExternalStorageDirectory().toString() + File.separator + fileName;
} else {// 系统下载缓存根目录的
filePath = Environment.getDownloadCacheDirectory().toString() + File.separator + fileName;
}
KLog.d(BaseConfig.LOG, "文件默认路径:" + filePath);
return filePath;
}
/**
* 将字符数据存储到手机中
*
* @param dataStr
* @param fileName
*/
public static String saveString(String dataStr, String fileName) {
// 获取默认的文件路径
String filePath = getFileDefaultPath(fileName);
try {
File file = new File(filePath);
if (!file.exists()) {
File dir = new File(file.getParent());
dir.mkdirs();
file.createNewFile();
}
FileOutputStream outStream = new FileOutputStream(file);
outStream.write(dataStr.getBytes());
outStream.close();
return filePath;
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
/**
* 追加文件:使用FileWriter
*
* @param fileName
* @param content
*/
public static void saveStringAppend(String fileName, String content) {
// 获取默认的文件路径
fileName = fileName + "_" + DateUtils.longToString(System.currentTimeMillis(), "yyyyMMdd") + ".txt";
String filePath = getFileDefaultPath(fileName);
FileWriter writer = null;
try {
// 打开一个写文件器,构造函数中的第二个参数true表示以追加形式写文件
writer = new FileWriter(filePath, true);
writer.write(content);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (writer != null) {
writer.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 将文件输入流写入指定目录
*
* @param inputStream 文件流
* @param filePath 存储路径
*/
public static void writeFile(InputStream inputStream, String filePath) throws Exception {
KLog.e(BaseConfig.LOG, "文件存储地址:" + filePath);
File file = new File(filePath);
// 若文件目录不存在则创建
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
// 若文件已存在则先删除
if (file.exists()) {
file.delete();
}
FileOutputStream fos;
fos = new FileOutputStream(file);
byte[] buffer = new byte[1024];
int len;
while ((len = inputStream.read(buffer)) != -1) {
// 写入文件
fos.write(buffer, 0, len);
}
inputStream.close();
fos.close();
}
/**
* 将指定的文件流写入指定的文件中
*
* @param in
* @param file
*/
public static void writeFile(InputStream in, File file) throws IOException {
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
if (file != null && file.exists()) {
file.delete();
}
FileOutputStream out = new FileOutputStream(file);
byte[] buffer = new byte[1024 * 128];
int len = -1;
while ((len = in.read(buffer)) != -1) {
out.write(buffer, 0, len);
}
out.flush();
out.close();
in.close();
}
/**
* 将图片存储到本地并在相冊中显示
*
* @param context
* @param bmp imageView转bitmap : ((BitmapDrawable) ivCode.getDrawable()).getBitmap()
*/
public static void saveImageToGallery(Context context, Bitmap bmp) {
// 首先保存图片
// File appDir = new File(Environment.getExternalStorageDirectory(), "si");
File appDir = new File(getAppExternalStoragePath());
if (!appDir.exists()) {
appDir.mkdir();
}
String fileName = System.currentTimeMillis() + ".png";
File file = new File(appDir, fileName);
KLog.d(BaseConfig.LOG, "path:" + file.getPath());
try {
FileOutputStream fos = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
// 其次把文件插入到系统图库
try {
MediaStore.Images.Media.insertImage(context.getContentResolver(),
file.getAbsolutePath(), fileName, null);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
// 最后通知图库更新
context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + file.getPath())));
Toast.makeText(context, "图片保存在:" + file.getPath(), Toast.LENGTH_SHORT).show();
}
/**
* 打开指定路径的文件
*
* @param activity
* @param fileName
* @return
*/
public static int openFile2(Activity activity, String fileName) {
try {
String filePath = getFileDefaultPath() + BaseConfig.FileAttachPath + File.separator + fileName;
File file = new File(filePath);
// 判断文件是否存在
// if (!file.exists()) {
// return 0;
// }
// 在MIME和文件类型的匹配表中找到对应的MIME类型
String fileType = filePath.substring(filePath.lastIndexOf("."), filePath.length()).toLowerCase();
String fileMIME = "*/*";
boolean isValidFileType = false;
for (int i = 0; i < FileUtils.MIME_MapTable.length; i++) {
if (fileType.equals(FileUtils.MIME_MapTable[i][0])) {
fileMIME = FileUtils.MIME_MapTable[i][1];
isValidFileType = true;
break;
}
}
if (!isValidFileType) {
return 1;
}
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.addCategory(Intent.CATEGORY_DEFAULT);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Uri uri;
if (Build.VERSION.SDK_INT >= 24) {
uri = FileProvider.getUriForFile(activity, BaseConfig.AUTHORITIES, file);
} else {
uri = Uri.fromFile(file);
}
intent.setDataAndType(uri, fileMIME);
activity.startActivity(Intent.createChooser(intent, ""));
return 2;
} catch (Exception e) {
KLog.d(BaseConfig.LOG, "打开文件error:" + e.getMessage());
return -1;
}
}
/**
* 通过文件uri获取到url文件路径。4.4之前
* 打开文件选择器后,通过onActivityForResult返回的uri获取选中文件地址
*
* @return 返回的文件路径。
*/
public static String getFilePath(Context context, Uri uri) {
String filename = null;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
filename = getPathByUri4kitkat(context, uri);
} else {
if ("content".equalsIgnoreCase(uri.getScheme())) {
Cursor cursor = null;
try {
//处理有些手机从文件管理器中获取文件失败问题。
cursor = context.getContentResolver().query(uri, new String[]{MediaStore.Images.ImageColumns.DATA}, null, null, null);
int column_index = cursor.getColumnIndexOrThrow("_data");
if (cursor.moveToFirst()) {
filename = cursor.getString(column_index);
}
} catch (Exception e) {
}
} else if ("file".equalsIgnoreCase(uri.getScheme())) {
filename = uri.toString().replace("file://", "");// 替换file://
if (!filename.startsWith("/mnt")) {// 加上"/mnt"头
filename += "/mnt";
}
}
}
return filename;
}
/**
* Android4.4以上从uri获取到文件路径
*
* @param context
* @param uri 文件URI
*/
@SuppressLint("NewApi")
public static String getPathByUri4kitkat(final Context context, final Uri uri) {
final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
// DocumentProvider
if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
if (isExternalStorageDocument(uri)) {// ExternalStorageProvider
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
if ("primary".equalsIgnoreCase(type)) {
return Environment.getExternalStorageDirectory() + "/" + split[1];
}
} else if (isDownloadsDocument(uri)) {// DownloadsProvider
final String id = DocumentsContract.getDocumentId(uri);
final Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"),
Long.valueOf(id));
return getDataColumn(context, contentUri, null, null);
} else if (isMediaDocument(uri)) {// MediaProvider
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
Uri contentUri = null;
if ("image".equals(type)) {
contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
} else if ("video".equals(type)) {
contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
} else if ("audio".equals(type)) {
contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
}
final String selection = "_id=?";
final String[] selectionArgs = new String[]{split[1]};
return getDataColumn(context, contentUri, selection, selectionArgs);
}
} else if ("content".equalsIgnoreCase(uri.getScheme())) {// MediaStore
return getDataColumn(context, uri, null, null);
} else if ("file".equalsIgnoreCase(uri.getScheme())) {// File
return uri.getPath();
}
return null;
}
/**
* 根据uri获取到数据列的值
* Get the value of the data column for this Uri. This is useful for
* MediaStore Uris, and other file-based ContentProviders.
*
* @param context The context.
* @param uri The Uri to query.
* @param selection (Optional) Filter used in the query.
* @param selectionArgs (Optional) Selection arguments used in the query.
* @return The value of the _data column, which is typically a file path.
*/
public static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {
Cursor cursor = null;
final String column = "_data";
final String[] projection = {column};
try {
cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);
if (cursor != null && cursor.moveToFirst()) {
final int column_index = cursor.getColumnIndexOrThrow(column);
return cursor.getString(column_index);
}
} finally {
if (cursor != null) {
cursor.close();
}
}
return null;
}
/**
* 判断是否为外部存储文件
*
* @param uri The Uri to check.
* @return Whether the Uri authority is ExternalStorageProvider.
*/
public static boolean isExternalStorageDocument(Uri uri) {
return "com.android.externalstorage.documents".equals(uri.getAuthority());
}
/**
* 判断是否为正在下载的文件
*
* @param uri The Uri to check.
* @return Whether the Uri authority is DownloadsProvider.
*/
public static boolean isDownloadsDocument(Uri uri) {
return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}
/**
* 判断是否是媒体文件
*
* @param uri The Uri to check.
* @return Whether the Uri authority is MediaProvider.
*/
public static boolean isMediaDocument(Uri uri) {
return "com.android.providers.media.documents".equals(uri.getAuthority());
}
/**
* 产生图片的路径,这里是在缓存目录下
*/
public static String generateImgePathInStoragePath() {
return getDir(ICON_DIR) + String.valueOf(System.currentTimeMillis()) + ".jpg";
}
public static String getImgePathInStoragePath() {
return getDir(ICON_DIR) + String.valueOf(System.currentTimeMillis());
}
/**
* 已登陆账号为标识存储图像
*
* @param phoneNo
* @return
*/
public static String getImgPathInStoragePath(String phoneNo) {
return getDir(ICON_DIR) + phoneNo + ".jpg";
}
/**
* 获取应用目录,当SD卡存在时,获取SD卡上的目录,当SD卡不存在时,获取应用的cache目录
*/
public static String getDir(String name) {
StringBuilder sb = new StringBuilder();
if (isSDCardAvailable()) {
sb.append(getAppExternalStoragePath());
} else {
sb.append(getFilesPath());
}
sb.append(name);
sb.append(File.separator);
String path = sb.toString();
if (createDirs(path)) {
return path;
} else {
return null;
}
}
/**
* 判断SD卡是否挂载
*/
public static boolean isSDCardAvailable() {
if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
return true;
} else {
return false;
}
}
/**
* 获取SD下当前APP的目录
*/
public static String getAppExternalStoragePath() {
StringBuilder sb = new StringBuilder();
sb.append(Environment.getExternalStorageDirectory().getAbsolutePath());
sb.append(File.separator);
sb.append(APP_STORAGE_ROOT);
sb.append(File.separator);
return sb.toString();
}
/**
* 获取应用的cache目录
*/
public static String getCachePath() {
File f = BaseApplication.context().getCacheDir();
if (null == f) {
return null;
} else {
return f.getAbsolutePath() + "/";
}
}
/**
* 获取应用的files目录
*/
public static String getFilesPath() {
File f = BaseApplication.context().getFilesDir();
if (null == f) {
return null;
} else {
return f.getAbsolutePath() + "/";
}
}
/**
* 创建文件夹
*/
public static boolean createDirs(String dirPath) {
File file = new File(dirPath);
if (!file.exists() || !file.isDirectory()) {
return file.mkdirs();
}
return true;
}
/**
* 将指定文件移动到指定位置
*
* @param filePath
* @param toFilePath
*/
public static void renameFile(String filePath, String toFilePath) {
KLog.e(BaseConfig.LOG, "将指定文件移动到指定位置 filePath:" + filePath + ",toFilePath:" + toFilePath);
try {
File toBeRenamed = new File(filePath);
//检查要重命名的文件是否存在,是否是文件
if (!toBeRenamed.exists() || toBeRenamed.isDirectory()) {
KLog.e(BaseConfig.LOG, "待更新文件不存在:" + filePath);
return;
}
File newFile = new File(toFilePath);
// 移动文件
toBeRenamed.renameTo(newFile);
KLog.e(BaseConfig.LOG, "将指定文件移动到指定位置完成");
} catch (Exception e) {
KLog.e(BaseConfig.LOG, "将指定文件移动到指定位置异常:" + e.getMessage());
}
}
/**
* 删除文件后更新数据库 通知媒体库更新文件夹
*
* @param context
* @param file
*/
public static void updateFileFromDatabase(Context context, File file) {
KLog.e(BaseConfig.LOG, "通知媒体库更新刷新 开始");
if (file != null) {
KLog.e(BaseConfig.LOG, "通知媒体库更新刷新 路径:" + file.getAbsolutePath());
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
String[] paths = new String[]{Environment.getExternalStorageDirectory().toString()};
MediaScannerConnection.scanFile(context, paths, null, null);
MediaScannerConnection.scanFile(
context,
new String[]{file.getAbsolutePath()},
null, new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
KLog.e(BaseConfig.LOG, "通知媒体库更新刷新 扫描完成 path:" + path);
}
});
} else {
context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://" + Environment.getExternalStorageDirectory())));
KLog.e(BaseConfig.LOG, "通知媒体库更新刷新 广播通知");
}
}
/**
* 按质量压缩bm
*
* @param bm
* @param quality 压缩率
* @return
*/
public static String saveBitmapByQuality(Bitmap bm, int quality, File file) {
String croppath = file.getAbsolutePath();
try {
FileOutputStream out = new FileOutputStream(file);
bm.compress(Bitmap.CompressFormat.JPEG, quality, out);
out.flush();
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
KLog.e(BaseConfig.LOG, "压缩图片的保存地址:" + croppath);
return croppath;
}
public static Bitmap decodeUriAsBitmap(Uri uri) {
Bitmap bitmap = null;
try {
// 先通过getContentResolver方法获得一个ContentResolver实例,
// 调用openInputStream(Uri)方法获得uri关联的数据流stream
// 把上一步获得的数据流解析成为bitmap
bitmap = BitmapFactory.decodeStream(BaseApplication.context().getContentResolver().openInputStream(uri));
} catch (FileNotFoundException e) {
e.printStackTrace();
return null;
}
return bitmap;
}
/**
* 缩放压缩
*
* @param bit
* @return
*/
public static Bitmap zoomPic(Bitmap bit) {
Bitmap bm = null;
try {
Matrix matrix = new Matrix();
matrix.setScale(0.5f, 0.5f);
bm = Bitmap.createBitmap(bit, 0, 0, bit.getWidth(), bit.getHeight(), matrix, true);
KLog.e(BaseConfig.LOG, "压缩后图片的大小" + (bm.getByteCount() / 1024 / 1024) + "M,宽度为" + bm.getWidth() + ",高度为" + bm.getHeight());
} catch (Exception e) {
KLog.e(BaseConfig.LOG, "缩放压缩异常:" + e.getMessage());
}
return bm;
}
/**
* 文件单位从Byte转换为MB
*
* @param size byte
* @return size MB
*/
public static boolean byteToMb(double size) {
KLog.e(BaseConfig.LOG, "计算文件大小 byte:" + size);
if (size <= 0) {
return false;
}
double megaByte = size / 1024 / 1024;
BigDecimal result1 = new BigDecimal(Double.toString(megaByte));
double megaByteValue = result1.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
KLog.d(BaseConfig.LOG, "fileSize:" + megaByteValue + "MB");
if (megaByteValue < BaseConfig.FileSieMax) {
return true;
}
return false;
}
/**
* 删除指定路径的图片
*
* @param filePath
*/
public static void deleteFile(String filePath) {
if (filePath != null && filePath.length() > 0) {
deleteFile(new File(filePath));
}
}
/**
* 删除指定文件
*
* @param file
*/
public static void deleteFile(File file) {
if (file != null && file.exists()) {
KLog.e(BaseConfig.LOG, "删除图片:" + file.getAbsolutePath());
file.delete();
}
}
/**
* 常见文件类型对应MIME类型
*/
public final static String[][] MIME_MapTable = {
//{后缀名,MIME类型}
{".3gp", "video/3gpp"},
{".apk", "application/vnd.android.package-archive"},
{".asf", "video/x-ms-asf"},
{".avi", "video/x-msvideo"},
{".bin", "application/octet-stream"},
{".bmp", "image/bmp"},
{".c", "text/plain"},
{".class", "application/octet-stream"},
{".conf", "text/plain"},
{".cpp", "text/plain"},
{".doc", "application/msword"},
{".docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"},
{".xls", "application/vnd.ms-excel"},
{".xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"},
{".exe", "application/octet-stream"},
{".gif", "image/gif"},
{".gtar", "application/x-gtar"},
{".gz", "application/x-gzip"},
{".h", "text/plain"},
{".htm", "text/html"},
{".html", "text/html"},
{".jar", "application/java-archive"},
{".java", "text/plain"},
{".jpeg", "image/jpeg"},
{".jpg", "image/jpeg"},
{".js", "application/x-javascript"},
{".log", "text/plain"},
{".m3u", "audio/x-mpegurl"},
{".m4a", "audio/mp4a-latm"},
{".m4b", "audio/mp4a-latm"},
{".m4p", "audio/mp4a-latm"},
{".m4u", "video/vnd.mpegurl"},
{".m4v", "video/x-m4v"},
{".mov", "video/quicktime"},
{".mp2", "audio/x-mpeg"},
{".mp3", "audio/x-mpeg"},
{".mp4", "video/mp4"},
{".mpc", "application/vnd.mpohun.certificate"},
{".mpe", "video/mpeg"},
{".mpeg", "video/mpeg"},
{".mpg", "video/mpeg"},
{".mpg4", "video/mp4"},
{".mpga", "audio/mpeg"},
{".msg", "application/vnd.ms-outlook"},
{".ogg", "audio/ogg"},
{".pdf", "application/pdf"},
{".png", "image/png"},
{".pps", "application/vnd.ms-powerpoint"},
{".ppt", "application/vnd.ms-powerpoint"},
{".pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation"},
{".prop", "text/plain"},
{".rc", "text/plain"},
{".rmvb", "audio/x-pn-realaudio"},
{".rtf", "application/rtf"},
{".sh", "text/plain"},
{".tar", "application/x-tar"},
{".tgz", "application/x-compressed"},
{".txt", "text/plain"},
{".wav", "audio/x-wav"},
{".wma", "audio/x-ms-wma"},
{".wmv", "audio/x-ms-wmv"},
{".wps", "application/vnd.ms-works"},
{".xml", "text/plain"},
{".z", "application/x-compress"},
{".zip", "application/x-zip-compressed"},
{"", "*/*"}
};
}
十、Base64工具类
import it.sauronsoftware.base64.Base64;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
/**
* * BASE64编码解码工具包 依赖javabase64-1.3.1.jar
*
* @ClassName Base64Util
* @author kokjuis 189155278@qq.com
* @date 2016-4-7
* @content
*/
public class Base64Util {
/** */
/**
* 文件读取缓冲区大小
*/
private static final int CACHE_SIZE = 1024;
/** */
/**
* <p>
* BASE64字符串解码为二进制数据
* </p>
*
* @param base64
* @return
* @throws Exception
*/
public static byte[] decode(String base64) throws Exception {
return Base64.decode(base64.getBytes());
}
/** */
/**
* <p>
* 二进制数据编码为BASE64字符串
* </p>
*
* @param bytes
* @return
* @throws Exception
*/
public static String encode(byte[] bytes) throws Exception {
return new String(Base64.encode(bytes));
}
/** */
/**
* <p>
* 将文件编码为BASE64字符串
* </p>
* <p>
* 大文件慎用,可能会导致内存溢出
* </p>
*
* @param filePath
* 文件绝对路径
* @return
* @throws Exception
*/
public static String encodeFile(String filePath) throws Exception {
byte[] bytes = fileToByte(filePath);
return encode(bytes);
}
/** */
/**
* <p>
* BASE64字符串转回文件
* </p>
*
* @param filePath
* 文件绝对路径
* @param base64
* 编码字符串
* @throws Exception
*/
public static void decodeToFile(String filePath, String base64)
throws Exception {
byte[] bytes = decode(base64);
byteArrayToFile(bytes, filePath);
}
/** */
/**
* <p>
* 文件转换为二进制数组
* </p>
*
* @param filePath
* 文件路径
* @return
* @throws Exception
*/
public static byte[] fileToByte(String filePath) throws Exception {
byte[] data = new byte[0];
File file = new File(filePath);
if (file.exists()) {
FileInputStream in = new FileInputStream(file);
ByteArrayOutputStream out = new ByteArrayOutputStream(2048);
byte[] cache = new byte[CACHE_SIZE];
int nRead = 0;
while ((nRead = in.read(cache)) != -1) {
out.write(cache, 0, nRead);
out.flush();
}
out.close();
in.close();
data = out.toByteArray();
}
return data;
}
/** */
/**
* <p>
* 二进制数据写文件
* </p>
*
* @param bytes
* 二进制数据
* @param filePath
* 文件生成目录
*/
public static void byteArrayToFile(byte[] bytes, String filePath)
throws Exception {
InputStream in = new ByteArrayInputStream(bytes);
File destFile = new File(filePath);
if (!destFile.getParentFile().exists()) {
destFile.getParentFile().mkdirs();
}
destFile.createNewFile();
OutputStream out = new FileOutputStream(destFile);
byte[] cache = new byte[CACHE_SIZE];
int nRead = 0;
while ((nRead = in.read(cache)) != -1) {
out.write(cache, 0, nRead);
out.flush();
}
out.close();
in.close();
}
}
十一、MD5工具类
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
/**
* MD5加密工具类
*
* @author dongdd
*/
public class MD5 {
/**
* md5加密
*
* @param str
* @return
*/
public static String MD5Encode(String str) {
try {
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(str.getBytes());
byte[] byteDigest = md.digest();
int i;
StringBuffer buf = new StringBuffer("");
for (int offset = 0; offset < byteDigest.length; offset++) {
i = byteDigest[offset];
if (i < 0)
i += 256;
if (i < 16)
buf.append("0");
buf.append(Integer.toHexString(i));
}
// 32位加密
return buf.toString();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
return null;
}
}
}
后续碰到了常用的再续加。