import android.content.Context;
import android.content.res.AssetManager;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import com.inks.inkslibrary.Utils.L;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.codec.digest.DigestUtils;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
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.math.BigInteger;
import java.security.MessageDigest;
import java.text.DecimalFormat;
public class FileUtils {
public static final int SIZETYPE_B = 1;//获取文件大小单位为B的double值
public static final int SIZETYPE_KB = 2;//获取文件大小单位为KB的double值
public static final int SIZETYPE_MB = 3;//获取文件大小单位为MB的double值
public static final int SIZETYPE_GB = 4;//获取文件大小单位为GB的double值
private static FileUtils instance;
private static final int SUCCESS = 1;
private static final int FAILED = 0;
private Context context;
private FileOperateCallback callback;
private volatile boolean isSuccess;
private String errorStr;
public static FileUtils getInstance(Context context) {
if (instance == null)
instance = new FileUtils(context);
return instance;
}
private FileUtils(Context context) {
this.context = context;
}
private Handler handler = new Handler(Looper.getMainLooper()) {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if (callback != null) {
if (msg.what == SUCCESS) {
callback.onSuccess();
}
if (msg.what == FAILED) {
callback.onFailed(msg.obj.toString());
}
}
}
};
public FileUtils copyAssetsToSD(final String srcPath, final String sdPath) {
new Thread(new Runnable() {
@Override
public void run() {
copyAssetsToDst(context, srcPath, sdPath);
if (isSuccess)
handler.obtainMessage(SUCCESS).sendToTarget();
else
handler.obtainMessage(FAILED, errorStr).sendToTarget();
}
}).start();
return this;
}
public void setFileOperateCallback(FileOperateCallback callback) {
this.callback = callback;
}
private void copyAssetsToDst(Context context, String srcPath, String dstPath) {
try {
String fileNames[] = context.getAssets().list(srcPath);
if (fileNames.length > 0) {
File file = new File(context.getExternalFilesDir(null), dstPath);
if (!file.exists()) file.mkdirs();
for (String fileName : fileNames) {
if (!srcPath.equals("")) { // assets 文件夹下的目录
copyAssetsToDst(context, srcPath + File.separator + fileName, dstPath + File.separator + fileName);
} else { // assets 文件夹
copyAssetsToDst(context, fileName, dstPath + File.separator + fileName);
}
}
} else {
File outFile = new File(context.getExternalFilesDir(null), dstPath);
L.e("outFile1:" + outFile.getPath());
L.e("outFile1:" + outFile.toString());
InputStream is = context.getAssets().open(srcPath);
FileOutputStream fos = new FileOutputStream(outFile);
byte[] buffer = new byte[1024];
int byteCount;
while ((byteCount = is.read(buffer)) != -1) {
fos.write(buffer, 0, byteCount);
}
fos.flush();
is.close();
fos.close();
}
isSuccess = true;
} catch (Exception e) {
e.printStackTrace();
errorStr = e.getMessage();
isSuccess = false;
}
}
public static void copyFromAssets(AssetManager assets, String source, String dest, boolean isCover)
throws IOException {
File file = new File(dest);
if (isCover || (!isCover && !file.exists())) {
InputStream is = null;
FileOutputStream fos = null;
try {
is = assets.open(source);
String path = dest;
fos = new FileOutputStream(path);
byte[] buffer = new byte[1024];
int size = 0;
while ((size = is.read(buffer, 0, 1024)) >= 0) {
fos.write(buffer, 0, size);
}
} finally {
if (fos != null) {
try {
fos.close();
} finally {
if (is != null) {
is.close();
}
}
}
}
}
}
public interface FileOperateCallback {
void onSuccess();
void onFailed(String error);
}
//判断文件是否存在
public static boolean fileIsExists(String strFile) {
try {
File f = new File(strFile);
if (!f.exists()) {
return false;
}
} catch (Exception e) {
return false;
}
return true;
}
//判断文件夹是否为空
public static boolean folderIsExists(String strFile) {
if (fileIsExists(strFile)) {
File file = new File(strFile);
File[] listFiles = file.listFiles();
if (listFiles.length > 0) {
return true;
} else {
return false;
}
} else {
return false;
}
}
/**
* 获取文件指定文件的指定单位的大小
*
* @param filePath 文件路径
* @param sizeType 获取大小的类型1为B、2为KB、3为MB、4为GB
* @return double值的大小
*/
public static double getFileOrFilesSize(String filePath, int sizeType) {
File file = new File(filePath);
long blockSize = 0;
try {
if (file.isDirectory()) {
blockSize = getFileSizes(file);
} else {
blockSize = getFileSize(file);
}
} catch (Exception e) {
e.printStackTrace();
Log.e("获取文件大小", "获取失败!");
}
return FormetFileSize(blockSize, sizeType);
}
/**
* 调用此方法自动计算指定文件或指定文件夹的大小
*
* @param filePath 文件路径
* @return 计算好的带B、KB、MB、GB的字符串
*/
public static String getAutoFileOrFilesSize(String filePath) {
File file = new File(filePath);
long blockSize = 0;
try {
if (file.isDirectory()) {
blockSize = getFileSizes(file);
} else {
blockSize = getFileSize(file);
}
} catch (Exception e) {
e.printStackTrace();
Log.e("获取文件大小", "获取失败!");
}
return FormetFileSize(blockSize);
}
/**
* @param radix 位 16 32 64
* @return
* @method 获取文件校验码
* @description
* @date: 2020/4/13 17:38
*/
public static String getFileMD5(String filePath, int radix) {
File file = new File(filePath);
if (!file.isFile()) {
return null;
}
MessageDigest digest = null;
FileInputStream in = null;
byte buffer[] = new byte[1024];
int len;
try {
digest = MessageDigest.getInstance("MD5");
in = new FileInputStream(file);
while ((len = in.read(buffer, 0, 1024)) != -1) {
digest.update(buffer, 0, len);
}
in.close();
} catch (Exception e) {
e.printStackTrace();
return null;
}
BigInteger bigInt = new BigInteger(1, digest.digest());
return bigInt.toString(radix);
}
public static String getFileHex(String filePath) {
File file = new File(filePath);
if (!file.isFile()) {
return "";
}
FileInputStream fileInputStream = null;
try {
fileInputStream = new FileInputStream(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
return "";
}
try {
return new String(Hex.encodeHex(DigestUtils.sha512(fileInputStream)));
//return DigestUtils.sha512Hex(fileInputStream);
} catch (Exception e) {
e.printStackTrace();
return "";
}
}
public static boolean checkHexMD5(String filePath, String hex) {
if (hex.equals(getFileMD5(filePath))) {
return true;
} else {
return false;
}
}
public static String getFileMD5(String filePath) {
File file = new File(filePath);
if (!file.isFile()) {
return "";
}
FileInputStream fileInputStream = null;
try {
fileInputStream = new FileInputStream(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
return "";
}
try {
return new String(Hex.encodeHex(DigestUtils.md5(fileInputStream)));
//return DigestUtils.md5Hex(fileInputStream);
} catch (Exception e) {
e.printStackTrace();
return "";
}
}
public static boolean checkMD5(String filePath, int radix, String md5) {
if (md5.equals(getFileMD5(filePath, radix))) {
return true;
} else {
return false;
}
}
public static boolean checkHex(String filePath, String hex) {
if (hex.equals(getFileHex(filePath))) {
return true;
} else {
return false;
}
}
/**
* 获取指定文件大小
*
* @param
* @return
* @throws Exception
*/
private static long getFileSize(File file) throws Exception {
long size = 0;
if (file.exists()) {
FileInputStream fis = null;
fis = new FileInputStream(file);
size = fis.available();
fis.close();
} else {
file.createNewFile();
Log.i("获取文件大小", "文件不存在!");
}
return size;
}
/**
* 获取指定文件夹
*
* @param f
* @return
* @throws Exception
*/
private static long getFileSizes(File f) throws Exception {
long size = 0;
File flist[] = f.listFiles();
for (int i = 0; i < flist.length; i++) {
if (flist[i].isDirectory()) {
size = size + getFileSizes(flist[i]);
} else {
size = size + getFileSize(flist[i]);
}
}
return size;
}
/**
* 转换文件大小
*
* @param fileS
* @return
*/
private static String FormetFileSize(long fileS) {
DecimalFormat df = new DecimalFormat("#.00");
String fileSizeString = "";
String wrongSize = "0B";
if (fileS == 0) {
return wrongSize;
}
if (fileS < 1024) {
fileSizeString = df.format((double) fileS) + "B";
} else if (fileS < 1048576) {
fileSizeString = df.format((double) fileS / 1024) + "KB";
} else if (fileS < 1073741824) {
fileSizeString = df.format((double) fileS / 1048576) + "MB";
} else {
fileSizeString = df.format((double) fileS / 1073741824) + "GB";
}
return fileSizeString;
}
/**
* 转换文件大小,指定转换的类型
*
* @param fileS
* @param sizeType
* @return
*/
private static double FormetFileSize(long fileS, int sizeType) {
DecimalFormat df = new DecimalFormat("#.00");
double fileSizeLong = 0;
switch (sizeType) {
case SIZETYPE_B:
fileSizeLong = Double.valueOf(df.format((double) fileS));
break;
case SIZETYPE_KB:
fileSizeLong = Double.valueOf(df.format((double) fileS / 1024));
break;
case SIZETYPE_MB:
fileSizeLong = Double.valueOf(df.format((double) fileS / 1048576));
break;
case SIZETYPE_GB:
fileSizeLong = Double.valueOf(df.format((double) fileS / 1073741824));
break;
default:
break;
}
return fileSizeLong;
}
/**
* 复制文件夹下的文件夹
*/
public static boolean copyDirList(File src, String dest){
if (!src.isDirectory()) {
return false;
}
File[] files = src.listFiles();
for (File file : files) {
if (file.isDirectory()) {
File destFile = new File(dest,file.getName());
L.e("开始复制文件夹:"+file.getName() +" 到"+destFile.getPath());
copyDirectory(file,destFile);
}
}
return true;
}
/**
* 复制文件夹
*/
public static boolean copyDirectory(File src, File dest) {
if (!src.isDirectory()) {
return false;
}
if (!dest.exists()) {
dest.mkdirs();
}
File[] files = src.listFiles();
for (File file : files) {
File destFile = new File(dest, file.getName());
if (file.isFile()) {
if (!copyFile(file, destFile)) {
return false;
}
} else if (file.isDirectory()) {
if (!copyDirectory(file, destFile)) {
return false;
}
}
}
return true;
}
/**
* 复制文件
*/
public static boolean copyFile(File src, File des) {
if (!src.exists()) {
Log.e("cppyFile", "file not exist:" + src.getAbsolutePath());
return false;
}
if (!des.getParentFile().isDirectory() && !des.getParentFile().mkdirs()) {
Log.e("cppyFile", "mkdir failed:" + des.getParent());
return false;
}
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
bis = new BufferedInputStream(new FileInputStream(src));
bos = new BufferedOutputStream(new FileOutputStream(des));
byte[] buffer = new byte[4 * 1024];
int count;
while ((count = bis.read(buffer, 0, buffer.length)) != -1) {
if (count > 0) {
bos.write(buffer, 0, count);
}
}
bos.flush();
return true;
} catch (Exception e) {
Log.e("copyFile", "exception:", e);
} finally {
if (bis != null) {
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (bos != null) {
try {
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return false;
}
public static void deleteFile(String path){
L.e("删除了:"+path);
File file = new File(path);
if(!file.exists()) return;
if(file.isFile() || file.list()==null) {
file.delete();
}else {
File[] files = file.listFiles();
for(File a:files) {
deleteFile(a.getPath());
}
file.delete();
}
}
public static void cleanFile(String path) {
File file = new File(path);
if (!file.exists()) return;
if (file.isFile() || file.list() == null) {
file.delete();
L.e("删除了" + file.getName());
} else {
File[] files = file.listFiles();
for (File a : files) {
cleanFile(a.getPath());
}
file.delete();
L.e("删除了" + file.getName());
}
}
}