package common.library.utils;
import android.annotation.SuppressLint;
import android.net.Uri;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.security.DigestInputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
/**
* @Author Liudeli
* @Describe:文件相關工具類
*/
public final class FileUtils {
private FileUtils() {
throw new UnsupportedOperationException("u can't instantiate me...");
}
private static final String LINE_SEP = System.getProperty("line.separator");
/**
* 根據文件路徑獲取文件
*
* @param filePath 文件路徑
* @return 文件
*/
public static File getFileByPath(final String filePath) {
return isSpace(filePath) ? null : new File(filePath);
}
/**
* 根據文件目錄路徑獲取子目錄名稱(不獲取二級子目錄)
* @param dirPath 文件路徑
* @return 文件目錄名稱
*/
public static List<String> getFiledirList(String dirPath){
if (dirPath == null || !isDir(dirPath)) return null;
List<String> stringList = new ArrayList<>();
File f = new File(dirPath);
File[] files = f.listFiles();
if(files != null&& files.length != 0){
for (File file : files) {
if (file.isDirectory()) {
stringList.add(file.getName());
}
}
}
return stringList;
}
/**
* 判斷文件是否存在
*
* @param filePath 文件路徑
* @return {@code true}: 存在<br>{@code false}: 不存在
*/
public static boolean isFileExists(final String filePath) {
return isFileExists(getFileByPath(filePath));
}
/**
* 判斷文件是否存在
*
* @param file 文件
* @return {@code true}: 存在<br>{@code false}: 不存在
*/
public static boolean isFileExists(final File file) {
return file != null && file.exists();
}
/**
* 重命名文件
*
* @param filePath 文件路徑
* @param newName 新名稱
* @return {@code true}: 重命名成功<br>{@code false}: 重命名失敗
*/
public static boolean rename(final String filePath, final String newName) {
return rename(getFileByPath(filePath), newName);
}
/**
* 重命名文件
*
* @param file 文件
* @param newName 新名稱
* @return {@code true}: 重命名成功<br>{@code false}: 重命名失敗
*/
public static boolean rename(final File file, final String newName) {
// 文件為空返回false
if (file == null) return false;
// 文件不存在返回false
if (!file.exists()) return false;
// 新的文件名為空返回false
if (isSpace(newName)) return false;
// 如果文件名沒有改變返回true
if (newName.equals(file.getName())) return true;
File newFile = new File(file.getParent() + File.separator + newName);
// 如果重命名的文件已存在返回false
return !newFile.exists()
&& file.renameTo(newFile);
}
/**
* 判斷是否是目錄
*
* @param dirPath 目錄路徑
* @return {@code true}: 是<br>{@code false}: 否
*/
public static boolean isDir(final String dirPath) {
return isDir(getFileByPath(dirPath));
}
/**
* 判斷是否是目錄
*
* @param file 文件
* @return {@code true}: 是<br>{@code false}: 否
*/
public static boolean isDir(final File file) {
return isFileExists(file) && file.isDirectory();
}
/**
* 判斷是否是文件
*
* @param filePath 文件路徑
* @return {@code true}: 是<br>{@code false}: 否
*/
public static boolean isFile(final String filePath) {
return isFile(getFileByPath(filePath));
}
/**
* 判斷是否是文件
*
* @param file 文件
* @return {@code true}: 是<br>{@code false}: 否
*/
public static boolean isFile(final File file) {
return isFileExists(file) && file.isFile();
}
/**
* 判斷目錄是否存在,不存在則判斷是否創建成功
*
* @param dirPath 目錄路徑
* @return {@code true}: 存在或創建成功<br>{@code false}: 不存在或創建失敗
*/
public static boolean createOrExistsDir(final String dirPath) {
return createOrExistsDir(getFileByPath(dirPath));
}
/**
* 判斷目錄是否存在,不存在則判斷是否創建成功
*
* @param file 文件
* @return {@code true}: 存在或創建成功<br>{@code false}: 不存在或創建失敗
*/
public static boolean createOrExistsDir(final File file) {
// 如果存在,是目錄則返回true,是文件則返回false,不存在則返回是否創建成功
return file != null && (file.exists() ? file.isDirectory() : file.mkdirs());
}
/**
* 判斷文件是否存在,不存在則判斷是否創建成功
*
* @param filePath 文件路徑
* @return {@code true}: 存在或創建成功<br>{@code false}: 不存在或創建失敗
*/
public static boolean createOrExistsFile(final String filePath) {
return createOrExistsFile(getFileByPath(filePath));
}
/**
* 判斷文件是否存在,不存在則判斷是否創建成功
*
* @param file 文件
* @return {@code true}: 存在或創建成功<br>{@code false}: 不存在或創建失敗
*/
public static boolean createOrExistsFile(final File file) {
if (file == null) return false;
// 如果存在,是文件則返回true,是目錄則返回false
if (file.exists()) return file.isFile();
if (!createOrExistsDir(file.getParentFile())) return false;
try {
return file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
/**
* 判斷文件是否存在,存在則在創建之前刪除
*
* @param file 文件
* @return {@code true}: 創建成功<br>{@code false}: 創建失敗
*/
public static boolean createFileByDeleteOldFile(final File file) {
if (file == null) return false;
// 文件存在並且刪除失敗返回false
if (file.exists() && !file.delete()) return false;
// 創建目錄失敗返回false
if (!createOrExistsDir(file.getParentFile())) return false;
try {
return file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
/**
* 復制或移動目錄
*
* @param srcDirPath 源目錄路徑
* @param destDirPath 目標目錄路徑
* @param isMove 是否移動
* @return {@code true}: 復制或移動成功<br>{@code false}: 復制或移動失敗
*/
private static boolean copyOrMoveDir(final String srcDirPath, final String destDirPath, final boolean isMove) {
return copyOrMoveDir(getFileByPath(srcDirPath), getFileByPath(destDirPath), isMove);
}
/**
* 復制或移動目錄
*
* @param srcDir 源目錄
* @param destDir 目標目錄
* @param isMove 是否移動
* @return {@code true}: 復制或移動成功<br>{@code false}: 復制或移動失敗
*/
private static boolean copyOrMoveDir(final File srcDir, final File destDir, final boolean isMove) {
if (srcDir == null || destDir == null) return false;
// 如果目標目錄在源目錄中則返回false,看不懂的話好好想想遞歸怎么結束
// srcPath : F:\\MyGithub\\AndroidUtilCode\\utilcode\\src\\test\\res
// destPath: F:\\MyGithub\\AndroidUtilCode\\utilcode\\src\\test\\res1
// 為防止以上這種情況出現出現誤判,須分別在后面加個路徑分隔符
String srcPath = srcDir.getPath() + File.separator;
String destPath = destDir.getPath() + File.separator;
if (destPath.contains(srcPath)) return false;
// 源文件不存在或者不是目錄則返回false
if (!srcDir.exists() || !srcDir.isDirectory()) return false;
// 目標目錄不存在返回false
if (!createOrExistsDir(destDir)) return false;
File[] files = srcDir.listFiles();
for (File file : files) {
File oneDestFile = new File(destPath + file.getName());
if (file.isFile()) {
// 如果操作失敗返回false
if (!copyOrMoveFile(file, oneDestFile, isMove)) return false;
} else if (file.isDirectory()) {
// 如果操作失敗返回false
if (!copyOrMoveDir(file, oneDestFile, isMove)) return false;
}
}
return !isMove || deleteDir(srcDir);
}
/**
* 復制或移動文件
*
* @param srcFilePath 源文件路徑
* @param destFilePath 目標文件路徑
* @param isMove 是否移動
* @return {@code true}: 復制或移動成功<br>{@code false}: 復制或移動失敗
*/
private static boolean copyOrMoveFile(final String srcFilePath, final String destFilePath, final boolean isMove) {
return copyOrMoveFile(getFileByPath(srcFilePath), getFileByPath(destFilePath), isMove);
}
/**
* 復制或移動文件
*
* @param srcFile 源文件
* @param destFile 目標文件
* @param isMove 是否移動
* @return {@code true}: 復制或移動成功<br>{@code false}: 復制或移動失敗
*/
private static boolean copyOrMoveFile(final File srcFile, final File destFile, final boolean isMove) {
if (srcFile == null || destFile == null) return false;
// 源文件不存在或者不是文件則返回false
if (!srcFile.exists() || !srcFile.isFile()) return false;
// 目標文件存在且是文件則返回false
if (destFile.exists() && destFile.isFile()) return false;
// 目標目錄不存在返回false
if (!createOrExistsDir(destFile.getParentFile())) return false;
try {
return FileIOUtils.writeFileFromIS(destFile, new FileInputStream(srcFile), false)
&& !(isMove && !deleteFile(srcFile));
} catch (FileNotFoundException e) {
e.printStackTrace();
return false;
}
}
/**
* 復制目錄
*
* @param srcDirPath 源目錄路徑
* @param destDirPath 目標目錄路徑
* @return {@code true}: 復制成功<br>{@code false}: 復制失敗
*/
public static boolean copyDir(final String srcDirPath, final String destDirPath) {
return copyDir(getFileByPath(srcDirPath), getFileByPath(destDirPath));
}
/**
* 復制目錄
*
* @param srcDir 源目錄
* @param destDir 目標目錄
* @return {@code true}: 復制成功<br>{@code false}: 復制失敗
*/
public static boolean copyDir(final File srcDir, final File destDir) {
return copyOrMoveDir(srcDir, destDir, false);
}
/**
* 復制文件
*
* @param srcFilePath 源文件路徑
* @param destFilePath 目標文件路徑
* @return {@code true}: 復制成功<br>{@code false}: 復制失敗
*/
public static boolean copyFile(final String srcFilePath, final String destFilePath) {
return copyFile(getFileByPath(srcFilePath), getFileByPath(destFilePath));
}
/**
* 復制文件
*
* @param srcFile 源文件
* @param destFile 目標文件
* @return {@code true}: 復制成功<br>{@code false}: 復制失敗
*/
public static boolean copyFile(final File srcFile, final File destFile) {
return copyOrMoveFile(srcFile, destFile, false);
}
/**
* 移動目錄
*
* @param srcDirPath 源目錄路徑
* @param destDirPath 目標目錄路徑
* @return {@code true}: 移動成功<br>{@code false}: 移動失敗
*/
public static boolean moveDir(final String srcDirPath, final String destDirPath) {
return moveDir(getFileByPath(srcDirPath), getFileByPath(destDirPath));
}
/**
* 移動目錄
*
* @param srcDir 源目錄
* @param destDir 目標目錄
* @return {@code true}: 移動成功<br>{@code false}: 移動失敗
*/
public static boolean moveDir(final File srcDir, final File destDir) {
return copyOrMoveDir(srcDir, destDir, true);
}
/**
* 移動文件
*
* @param srcFilePath 源文件路徑
* @param destFilePath 目標文件路徑
* @return {@code true}: 移動成功<br>{@code false}: 移動失敗
*/
public static boolean moveFile(final String srcFilePath, final String destFilePath) {
Log.e("xxx","移動文件"+srcFilePath+"---->"+destFilePath);
return moveFile(getFileByPath(srcFilePath), getFileByPath(destFilePath));
}
/**
* 移動文件
*
* @param srcFile 源文件
* @param destFile 目標文件
* @return {@code true}: 移動成功<br>{@code false}: 移動失敗
*/
public static boolean moveFile(final File srcFile, final File destFile) {
return copyOrMoveFile(srcFile, destFile, true);
}
/**
* 刪除目錄
*
* @param dirPath 目錄路徑
* @return {@code true}: 刪除成功<br>{@code false}: 刪除失敗
*/
public static boolean deleteDir(final String dirPath) {
return deleteDir(getFileByPath(dirPath));
}
/**
* 刪除文件或目錄
* @param file
* @return
*/
public static boolean deleteDirOrFile(File file){
if (file == null) return false;
if (!file.exists()) return false;
if(file.isFile()){
return deleteFile(file);
}else{
return deleteDir(file);
}
}
/**
* 刪除文件或目錄
* @param path
* @return
*/
public static boolean deleteDirOrFile(String path){
return deleteDirOrFile(getFileByPath(path));
}
/**
* 刪除目錄
*
* @param dir 目錄
* @return {@code true}: 刪除成功<br>{@code false}: 刪除失敗
*/
public static boolean deleteDir(final File dir) {
if (dir == null) return false;
// 目錄不存在返回true
if (!dir.exists()) return true;
// 不是目錄返回false
if (!dir.isDirectory()) return false;
// 現在文件存在且是文件夾
File[] files = dir.listFiles();
if (files != null && files.length != 0) {
for (File file : files) {
if (file.isFile()) {
if (!file.delete()) return false;
} else if (file.isDirectory()) {
if (!deleteDir(file)) return false;
}
}
}
return dir.delete();
}
/**
* 刪除Luban文件集合 以“|” 分割
* @param srcFilePaths
*/
public static void deleteFiles(String srcFilePaths){
if(TextUtils.isEmpty(srcFilePaths))
return;
List<String> list = Arrays.asList(srcFilePaths.split("\\|"));
for(String path : list){
if(path.contains("luban")){
deleteFile(path);
}
}
}
/**
* 刪除文件
*
* @param srcFilePath 文件路徑
* @return {@code true}: 刪除成功<br>{@code false}: 刪除失敗
*/
public static boolean deleteFile(final String srcFilePath) {
return deleteFile(getFileByPath(srcFilePath));
}
/**
* 刪除文件
*
* @param file 文件
* @return {@code true}: 刪除成功<br>{@code false}: 刪除失敗
*/
public static boolean deleteFile(final File file) {
return file != null && (!file.exists() || file.isFile() && file.delete());
}
/**
* 刪除目錄下的所有文件
*
* @param dirPath 目錄路徑
* @return {@code true}: 刪除成功<br>{@code false}: 刪除失敗
*/
public static boolean deleteFilesInDir(final String dirPath) {
return deleteFilesInDir(getFileByPath(dirPath));
}
/**
* 刪除目錄下的所有文件
*
* @param dir 目錄
* @return {@code true}: 刪除成功<br>{@code false}: 刪除失敗
*/
public static boolean deleteFilesInDir(final File dir) {
if (dir == null) return false;
// 目錄不存在返回true
if (!dir.exists()) return true;
// 不是目錄返回false
if (!dir.isDirectory()) return false;
// 現在文件存在且是文件夾
File[] files = dir.listFiles();
if (files != null && files.length != 0) {
for (File file : files) {
if (file.isFile()) {
if (!file.delete()) return false;
} else if (file.isDirectory()) {
if (!deleteDir(file)) return false;
}
}
}
return true;
}
/**
* 獲取目錄下所有文件
*
* @param dirPath 目錄路徑
* @param isRecursive 是否遞歸進子目錄
* @return 文件鏈表
*/
public static List<File> listFilesInDir(final String dirPath, final boolean isRecursive) {
return listFilesInDir(getFileByPath(dirPath), isRecursive);
}
/**
* 獲取目錄下所有文件
*
* @param dir 目錄
* @param isRecursive 是否遞歸進子目錄
* @return 文件鏈表
*/
public static List<File> listFilesInDir(final File dir, final boolean isRecursive) {
if (!isDir(dir)) return null;
if (isRecursive) return listFilesInDir(dir);
List<File> list = new ArrayList<>();
File[] files = dir.listFiles();
if (files != null && files.length != 0) {
Collections.addAll(list, files);
}
return list;
}
/**
* 獲取目錄下所有文件包括子目錄
*
* @param dirPath 目錄路徑
* @return 文件鏈表
*/
public static List<File> listFilesInDir(final String dirPath) {
return listFilesInDir(getFileByPath(dirPath));
}
/**
* 獲取目錄下所有文件包括子目錄
*
* @param dir 目錄
* @return 文件鏈表
*/
public static List<File> listFilesInDir(final File dir) {
if (!isDir(dir)) return null;
List<File> list = new ArrayList<>();
File[] files = dir.listFiles();
if (files != null && files.length != 0) {
for (File file : files) {
list.add(file);
if (file.isDirectory()) {
List<File> fileList = listFilesInDir(file);
if (fileList != null) {
list.addAll(fileList);
}
}
}
}
return list;
}
/**
* 獲取目錄下所有后綴名為suffix的文件
* <p>大小寫忽略</p>
*
* @param dirPath 目錄路徑
* @param suffix 后綴名
* @param isRecursive 是否遞歸進子目錄
* @return 文件鏈表
*/
public static List<File> listFilesInDirWithFilter(final String dirPath, final String suffix, final boolean isRecursive) {
return listFilesInDirWithFilter(getFileByPath(dirPath), suffix, isRecursive);
}
/**
* 獲取目錄下所有后綴名為suffix的文件
* <p>大小寫忽略</p>
*
* @param dir 目錄
* @param suffix 后綴名
* @param isRecursive 是否遞歸進子目錄
* @return 文件鏈表
*/
public static List<File> listFilesInDirWithFilter(final File dir, final String suffix, final boolean isRecursive) {
if (isRecursive) return listFilesInDirWithFilter(dir, suffix);
if (dir == null || !isDir(dir)) return null;
List<File> list = new ArrayList<>();
File[] files = dir.listFiles();
if (files != null && files.length != 0) {
for (File file : files) {
if(file.length()>10){
if (file.getName().toUpperCase().endsWith(suffix.toUpperCase())) {
list.add(file);
}
}
}
}
return list;
}
/**
* 獲取目錄下所有后綴名為suffix的文件包括子目錄
* <p>大小寫忽略</p>
*
* @param dirPath 目錄路徑
* @param suffix 后綴名
* @return 文件鏈表
*/
public static List<File> listFilesInDirWithFilter(final String dirPath, final String suffix) {
return listFilesInDirWithFilter(getFileByPath(dirPath), suffix);
}
/**
* 獲取目錄下所有后綴名為suffix的文件包括子目錄
* <p>大小寫忽略</p>
*
* @param dir 目錄
* @param suffix 后綴名
* @return 文件鏈表
*/
public static List<File> listFilesInDirWithFilter(final File dir, final String suffix) {
if (dir == null || !isDir(dir)) return null;
List<File> list = new ArrayList<>();
File[] files = dir.listFiles();
if (files != null && files.length != 0) {
for (File file : files) {
if (file.getName().toUpperCase().endsWith(suffix.toUpperCase())) {
list.add(file);
}
if (file.isDirectory()) {
list.addAll(listFilesInDirWithFilter(file, suffix));
}
}
}
return list;
}
/**
* 獲取目錄下所有符合filter的文件
*
* @param dirPath 目錄路徑
* @param filter 過濾器
* @param isRecursive 是否遞歸進子目錄
* @return 文件鏈表
*/
public static List<File> listFilesInDirWithFilter(final String dirPath, final FilenameFilter filter, final boolean isRecursive) {
return listFilesInDirWithFilter(getFileByPath(dirPath), filter, isRecursive);
}
/**
* 獲取目錄下所有符合filter的文件
*
* @param dir 目錄
* @param filter 過濾器
* @param isRecursive 是否遞歸進子目錄
* @return 文件鏈表
*/
public static List<File> listFilesInDirWithFilter(final File dir, final FilenameFilter filter, final boolean isRecursive) {
if (isRecursive) return listFilesInDirWithFilter(dir, filter);
if (dir == null || !isDir(dir)) return null;
List<File> list = new ArrayList<>();
File[] files = dir.listFiles();
if (files != null && files.length != 0) {
for (File file : files) {
if (filter.accept(file.getParentFile(), file.getName())) {
list.add(file);
}
}
}
return list;
}
/**
* 獲取目錄下所有符合filter的文件包括子目錄
*
* @param dirPath 目錄路徑
* @param filter 過濾器
* @return 文件鏈表
*/
public static List<File> listFilesInDirWithFilter(final String dirPath, final FilenameFilter filter) {
return listFilesInDirWithFilter(getFileByPath(dirPath), filter);
}
/**
* 獲取目錄下所有符合filter的文件包括子目錄
*
* @param dir 目錄
* @param filter 過濾器
* @return 文件鏈表
*/
public static List<File> listFilesInDirWithFilter(final File dir, final FilenameFilter filter) {
if (dir == null || !isDir(dir)) return null;
List<File> list = new ArrayList<>();
File[] files = dir.listFiles();
if (files != null && files.length != 0) {
for (File file : files) {
if (filter.accept(file.getParentFile(), file.getName())) {
list.add(file);
}
if (file.isDirectory()) {
list.addAll(listFilesInDirWithFilter(file, filter));
}
}
}
return list;
}
/**
* 獲取目錄下指定文件名的文件包括子目錄
* <p>大小寫忽略</p>
*
* @param dirPath 目錄路徑
* @param fileName 文件名
* @return 文件鏈表
*/
public static List<File> searchFileInDir(final String dirPath, final String fileName) {
return searchFileInDir(getFileByPath(dirPath), fileName);
}
/**
* 獲取目錄下指定文件名的文件包括子目錄
* <p>大小寫忽略</p>
*
* @param dir 目錄
* @param fileName 文件名
* @return 文件鏈表
*/
public static List<File> searchFileInDir(final File dir, final String fileName) {
if (dir == null || !isDir(dir)) return null;
List<File> list = new ArrayList<>();
File[] files = dir.listFiles();
if (files != null && files.length != 0) {
for (File file : files) {
if (file.getName().toUpperCase().equals(fileName.toUpperCase())) {
list.add(file);
}
if (file.isDirectory()) {
list.addAll(searchFileInDir(file, fileName));
}
}
}
return list;
}
/**
* 獲取文件最后修改的毫秒時間戳
*
* @param filePath 文件路徑
* @return 文件最后修改的毫秒時間戳
*/
public static long getFileLastModified(final String filePath) {
return getFileLastModified(getFileByPath(filePath));
}
/**
* 獲取文件最后修改的毫秒時間戳
*
* @param file 文件
* @return 文件最后修改的毫秒時間戳
*/
public static long getFileLastModified(final File file) {
if (file == null) return -1;
return file.lastModified();
}
/**
* 簡單獲取文件編碼格式
*
* @param filePath 文件路徑
* @return 文件編碼
*/
public static String getFileCharsetSimple(final String filePath) {
return getFileCharsetSimple(getFileByPath(filePath));
}
/**
* 簡單獲取文件編碼格式
*
* @param file 文件
* @return 文件編碼
*/
public static String getFileCharsetSimple(final File file) {
int p = 0;
InputStream is = null;
try {
is = new BufferedInputStream(new FileInputStream(file));
p = (is.read() << 8) + is.read();
} catch (IOException e) {
e.printStackTrace();
} finally {
CloseUtils.closeIO(is);
}
switch (p) {
case 0xefbb:
return "UTF-8";
case 0xfffe:
return "Unicode";
case 0xfeff:
return "UTF-16BE";
default:
return "GBK";
}
}
/**
* 獲取文件行數
*
* @param filePath 文件路徑
* @return 文件行數
*/
public static int getFileLines(final String filePath) {
return getFileLines(getFileByPath(filePath));
}
/**
* 獲取文件行數
* <p>比readLine要快很多</p>
*
* @param file 文件
* @return 文件行數
*/
public static int getFileLines(final File file) {
int count = 1;
InputStream is = null;
try {
is = new BufferedInputStream(new FileInputStream(file));
byte[] buffer = new byte[1024];
int readChars;
if (LINE_SEP.endsWith("\n")) {
while ((readChars = is.read(buffer, 0, 1024)) != -1) {
for (int i = 0; i < readChars; ++i) {
if (buffer[i] == '\n') ++count;
}
}
} else {
while ((readChars = is.read(buffer, 0, 1024)) != -1) {
for (int i = 0; i < readChars; ++i) {
if (buffer[i] == '\r') ++count;
}
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
CloseUtils.closeIO(is);
}
return count;
}
/**
* 獲取目錄大小
*
* @param dirPath 目錄路徑
* @return 文件大小
*/
public static String getDirSize(final String dirPath) {
return getDirSize(getFileByPath(dirPath));
}
/**
* 獲取目錄大小
*
* @param dir 目錄
* @return 文件大小
*/
public static String getDirSize(final File dir) {
long len = getDirLength(dir);
return len == -1 ? "" : byte2FitMemorySize(len);
}
/**
* 獲取文件大小
*
* @param filePath 文件路徑
* @return 文件大小
*/
public static String getFileSize(final String filePath) {
return getFileSize(getFileByPath(filePath));
}
/**
* 獲取文件大小
*
* @param file 文件
* @return 文件大小
*/
public static String getFileSize(final File file) {
long len = getFileLength(file);
return len == -1 ? "" : byte2FitMemorySize(len);
}
/**
* 獲取目錄長度
*
* @param dirPath 目錄路徑
* @return 目錄長度
*/
public static long getDirLength(final String dirPath) {
return getDirLength(getFileByPath(dirPath));
}
/**
* 獲取目錄長度
*
* @param dir 目錄
* @return 目錄長度
*/
public static long getDirLength(final File dir) {
if (!isDir(dir)) return -1;
long len = 0;
File[] files = dir.listFiles();
if (files != null && files.length != 0) {
for (File file : files) {
if (file.isDirectory()) {
len += getDirLength(file);
} else {
len += file.length();
}
}
}
return len;
}
/**
* 獲取文件長度
*
* @param filePath 文件路徑
* @return 文件長度
*/
public static long getFileLength(final String filePath) {
return getFileLength(getFileByPath(filePath));
}
/**
* 獲取文件長度
*
* @param file 文件
* @return 文件長度
*/
public static long getFileLength(final File file) {
if (!isFile(file)) return -1;
return file.length();
}
/**
* 獲取文件的MD5校驗碼
*
* @param filePath 文件路徑
* @return 文件的MD5校驗碼
*/
public static String getFileMD5ToString(final String filePath) {
File file = isSpace(filePath) ? null : new File(filePath);
return getFileMD5ToString(file);
}
/**
* 獲取文件的MD5校驗碼
*
* @param filePath 文件路徑
* @return 文件的MD5校驗碼
*/
public static byte[] getFileMD5(final String filePath) {
File file = isSpace(filePath) ? null : new File(filePath);
return getFileMD5(file);
}
/**
* 獲取文件的MD5校驗碼
*
* @param file 文件
* @return 文件的MD5校驗碼
*/
public static String getFileMD5ToString(final File file) {
return bytes2HexString(getFileMD5(file));
}
/**
* 獲取文件的MD5校驗碼
*
* @param file 文件
* @return 文件的MD5校驗碼
*/
public static byte[] getFileMD5(final File file) {
if (file == null) return null;
DigestInputStream dis = null;
try {
FileInputStream fis = new FileInputStream(file);
MessageDigest md = MessageDigest.getInstance("MD5");
dis = new DigestInputStream(fis, md);
byte[] buffer = new byte[1024 * 256];
while (true) {
if (!(dis.read(buffer) > 0)) break;
}
md = dis.getMessageDigest();
return md.digest();
} catch (NoSuchAlgorithmException | IOException e) {
e.printStackTrace();
} finally {
CloseUtils.closeIO(dis);
}
return null;
}
/**
* 獲取全路徑中的最長目錄
*
* @param file 文件
* @return filePath最長目錄
*/
public static String getDirName(final File file) {
if (file == null) return null;
return getDirName(file.getPath());
}
/**
* 獲取全路徑中的最長目錄
*
* @param filePath 文件路徑
* @return filePath最長目錄
*/
public static String getDirName(final String filePath) {
if (isSpace(filePath)) return filePath;
int lastSep = filePath.lastIndexOf(File.separator);
return lastSep == -1 ? "" : filePath.substring(0, lastSep + 1);
}
/**
* 獲取全路徑中的文件名
*
* @param file 文件
* @return 文件名
*/
public static String getFileName(final File file) {
if (file == null) return null;
return getFileName(file.getPath());
}
/**
* 獲取全路徑中的文件名
*
* @param filePath 文件路徑
* @return 文件名
*/
public static String getFileName(final String filePath) {
if (isSpace(filePath)) return filePath;
int lastSep = filePath.lastIndexOf(File.separator);
return lastSep == -1 ? filePath : filePath.substring(lastSep + 1);
}
/**
* 獲取全路徑中的不帶拓展名的文件名
*
* @param file 文件
* @return 不帶拓展名的文件名
*/
public static String getFileNameNoExtension(final File file) {
if (file == null) return null;
return getFileNameNoExtension(file.getPath());
}
/**
* 獲取全路徑中的不帶拓展名的文件名
*
* @param filePath 文件路徑
* @return 不帶拓展名的文件名
*/
public static String getFileNameNoExtension(final String filePath) {
if (isSpace(filePath)) return filePath;
int lastPoi = filePath.lastIndexOf('.');
int lastSep = filePath.lastIndexOf(File.separator);
if (lastSep == -1) {
return (lastPoi == -1 ? filePath : filePath.substring(0, lastPoi));
}
if (lastPoi == -1 || lastSep > lastPoi) {
return filePath.substring(lastSep + 1);
}
return filePath.substring(lastSep + 1, lastPoi);
}
/**
* 獲取全路徑中的文件拓展名
*
* @param file 文件
* @return 文件拓展名
*/
public static String getFileExtension(final File file) {
if (file == null) return null;
return getFileExtension(file.getPath());
}
/**
* 獲取全路徑中的文件拓展名
*
* @param filePath 文件路徑
* @return 文件拓展名
*/
public static String getFileExtension(final String filePath) {
if (isSpace(filePath)) return filePath;
int lastPoi = filePath.lastIndexOf('.');
int lastSep = filePath.lastIndexOf(File.separator);
if (lastPoi == -1 || lastSep >= lastPoi) return "";
return filePath.substring(lastPoi + 1);
}
/**
* 根據文件類型去刪除其在系統中對應的Media數據庫
* @param file
* @return -1代表不是媒體文件,0表示在數據庫中查找不到,1找到數據庫中對應的數據,並且刪除
*/
public static int deleteMedia(File file){
String name = file.getName();
String path = file.getAbsolutePath();
if(name.contains(".jpg") || name.contains(".mp4")){
Uri MEDIA_URI = null;
if(name.contains(".jpg")){
if(path.contains("mnt/sdcard/")){
MEDIA_URI = MediaStore.Images.Media.INTERNAL_CONTENT_URI;
path = path.replace("/mnt/sdcard/", "/storage/sdcard0/");
}else if(file.getAbsolutePath().contains("mnt/sdcard2/")){
MEDIA_URI = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
path = path.replace("/mnt/sdcard2/","/storage/sdcard1/");
}
}else{
if(path.contains("mnt/sdcard/")){
MEDIA_URI = MediaStore.Video.Media.INTERNAL_CONTENT_URI;
path = path.replace("/mnt/sdcard1/","/storage/sdcard0/");
}else if(file.getAbsolutePath().contains("mnt/sdcard2/")){
MEDIA_URI = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
path = path.replace("/mnt/sdcard2/","/storage/sdcard1/");
}
}
int resultCode = 0 ;
// resultCode = MyApp.getInstance().getContentResolver().delete(MEDIA_URI, MediaStore.Images.Media.DATA+"="+"'"+path+"'" , null);
return resultCode;
}else{
return -1;
}
}
///////////////////////////////////////////////////////////////////////////
// copy from ConvertUtils
///////////////////////////////////////////////////////////////////////////
private static final char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
/**
* byteArr轉hexString
* <p>例如:</p>
* bytes2HexString(new byte[] { 0, (byte) 0xa8 }) returns 00A8
*
* @param bytes 字節數組
* @return 16進制大寫字符串
*/
private static String bytes2HexString(final byte[] bytes) {
if (bytes == null) return null;
int len = bytes.length;
if (len <= 0) return null;
char[] ret = new char[len << 1];
for (int i = 0, j = 0; i < len; i++) {
ret[j++] = hexDigits[bytes[i] >>> 4 & 0x0f];
ret[j++] = hexDigits[bytes[i] & 0x0f];
}
return new String(ret);
}
/**
* 字節數轉合適內存大小
* <p>保留3位小數</p>
*
* @param byteNum 字節數
* @return 合適內存大小
*/
@SuppressLint("DefaultLocale")
private static String byte2FitMemorySize(final long byteNum) {
if (byteNum < 0) {
return "shouldn't be less than zero!";
} else if (byteNum < 1024) {
return String.format("%.3fB", (double) byteNum + 0.0005);
} else if (byteNum < 1048576) {
return String.format("%.3fKB", (double) byteNum / 1024 + 0.0005);
} else if (byteNum < 1073741824) {
return String.format("%.3fMB", (double) byteNum / 1048576 + 0.0005);
} else {
return String.format("%.3fGB", (double) byteNum / 1073741824 + 0.0005);
}
}
private static boolean isSpace(final String s) {
if (s == null) return true;
for (int i = 0, len = s.length(); i < len; ++i) {
if (!Character.isWhitespace(s.charAt(i))) {
return false;
}
}
return true;
}
// ---------------
/**
* 在指定的位置創建指定的文件
* @param filePath 完整的文件路徑
* @param mkdir 是否創建相關的文件夾
* @throws IOException
*/
public static void mkFile(String filePath, boolean mkdir) throws IOException{
File file = new File(filePath);
/**
* mkdirs()創建多層目錄,mkdir()創建單層目錄
* writeObject時才創建磁盤文件。
* 若不創建文件,readObject出錯。
*/
file.getParentFile().mkdirs();
file.createNewFile();
file = null;
}
/**
* 在指定的位置創建文件夾
* @param dirPath 文件夾路徑
* @return 若創建成功,則返回True;反之,則返回False
*/
public static boolean mkDir(String dirPath) {
return new File(dirPath).mkdirs();
}
/**
* 刪除指定的文件
* @param filePath 文件路徑
* @return 若刪除成功,則返回True;反之,則返回False
*/
public static boolean delFile(String filePath) {
return new File(filePath).delete();
}
/**
* 刪除指定的文件夾
* @param dirPath 文件夾路徑
* @param delFile 文件夾中是否包含文件
* @return 若刪除成功,則返回True;反之,則返回False
*/
public static boolean delDir(String dirPath, boolean delFile) {
if (delFile) {
File file = new File(dirPath);
if (file.isFile()) {
return file.delete();
} else if (file.isDirectory()) {
if (file.listFiles().length == 0) {
return file.delete();
} else {
int zFiles = file.listFiles().length;
File[] delfile = file.listFiles();
for (int i = 0; i < zFiles; i++) {
if (delfile[i].isDirectory()) {
delDir(delfile[i].getAbsolutePath(), true);
}
delfile[i].delete();
}
return file.delete();
}
} else {
return false;
}
} else {
return new File(dirPath).delete();
}
}
/**
* 復制文件/文件夾 若要進行文件夾復制,請勿將目標文件夾置於源文件夾中
* @param source 源文件(夾)
* @param target 目標文件(夾)
* @param isFolder 若進行文件夾復制,則為True;反之為False
* @throws IOException
*/
public static void copy(String source, String target, boolean isFolder) throws IOException{
if (isFolder) {
new File(target).mkdirs();
File a = new File(source);
String[] file = a.list();
File temp = null;
for (int i = 0; i < file.length; i++) {
if (source.endsWith(File.separator)) {
temp = new File(source + file[i]);
} else {
temp = new File(source + File.separator + file[i]);
}
if (temp.isFile()) {
FileInputStream input = new FileInputStream(temp);
FileOutputStream output = new FileOutputStream(target + File.separator + temp.getName().toString());
byte[] b = new byte[1024];
int len;
while ((len = input.read(b)) != -1) {
output.write(b, 0, len);
}
output.flush();
output.close();
input.close();
} if (temp.isDirectory()) {
copy(source + File.separator + file[i], target + File.separator + file[i], true);
}
}
} else {
int byteread = 0;
File oldfile = new File(source);
if (oldfile.exists()) {
InputStream inputStream = new FileInputStream(source);
File file = new File(target);
file.getParentFile().mkdirs();
file.createNewFile();
FileOutputStream outputStream = new FileOutputStream(file);
byte[] buffer = new byte[1024];
while ((byteread = inputStream.read(buffer)) != -1){
outputStream.write(buffer, 0, byteread);
}
inputStream.close();
outputStream.close();
}
}
}
}