你想要的这都有-Android文件工具类FileUtils

2024-06-01 08:08

本文主要是介绍你想要的这都有-Android文件工具类FileUtils,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

包含所有关于文件处理的工具类

/**
* 对文件处理的工具类
*/
public class FileUtils {
/**
* 获取可以使用的缓存目录(默认目录名/itlanbaoApp/)
* @param context
* @return
*/
public static File getDiskCacheDir(Context context) {
return getDiskCacheDir(context, FileConstants.RESOURCE_DIRECTORY);
}

/*** 获取可以使用的缓存目录* @param context* @param uniqueName 目录名称* @return*/
public static File getDiskCacheDir(Context context, String uniqueName) {final String cachePath = checkSDCard() ? getExternalCacheDir(context).getPath() : getAppCacheDir(context);File cacheDirFile = new File(cachePath);if (!cacheDirFile.exists()) {cacheDirFile.mkdirs();}return cacheDirFile;
}/*** 获取程序外部的缓存目录* @param context* @return*/public static File getExternalCacheDir(Context context) {// 这个sd卡中文件路径下的内容会随着,程序卸载或者设置中清除缓存后一起清空final String cacheDir = "/Android/data/" + context.getPackageName() + "/cache/";return new File(Environment.getExternalStorageDirectory().getPath() + cacheDir);}/*** 获取文件路径空间大小* @param path* @return*/public static long getUsableSpace(File path) {try{final StatFs stats = new StatFs(path.getPath());return (long) stats.getBlockSize() * (long) stats.getAvailableBlocks();}catch (Exception e) {e.printStackTrace();return -1;}}/*** 空间大小单位格式化* @param size* @return*/public static String formatSize(long size) {

// Formatter.formatFileSize()
String suffix = null;
float fSize=0;

     if (size >= 1024) {suffix = "KB";fSize=size / 1024;if (fSize >= 1024) {suffix = "MB";fSize /= 1024;}if (fSize >= 1024) {suffix = "GB";fSize /= 1024;}} else {fSize = size;}java.text.DecimalFormat df = new java.text.DecimalFormat("#0.00");StringBuilder resultBuffer = new StringBuilder(df.format(fSize));if (suffix != null)resultBuffer.append(suffix);return resultBuffer.toString();}/*** 检查SD卡是否存在** @return*/
public static boolean checkSDCard() {final String status = Environment.getExternalStorageState();if (Environment.MEDIA_MOUNTED.equals(status)) {return true;}return false;
}/*** 获取安装在用户手机上的com.itlanbao.app下的files目录** @return files path*/
public static String getAppFilesDir(Context context) {return context.getFilesDir().getAbsolutePath();
}/*** 获取安装在用户手机上的com.itlanbao.yyapp下的cache目录** @return cache path*/
public static String getAppCacheDir(Context context) {return context.getCacheDir().getPath();
}/*** 创建app主目录** @return boolean*/
public static boolean checkFileDirectory(Context context) {final File resDir = FileUtils.getDiskCacheDir(context);if (!resDir.exists()) {return resDir.mkdirs();}return true;
}/*** 创建缓存文件夹*/
public static void initCacheFile(Context context) {if (LogUtils.DEBUG) {LogUtils.v("initCacheFile");}final String cacheDir = FileUtils.getDiskCacheDir(context).getAbsolutePath();final String imageDirPath = cacheDir + FileConstants.CACHE_IMAGE_DIR;final File imageFileDir = new File(imageDirPath);if (!imageFileDir.exists()) {boolean isOk = imageFileDir.mkdirs();if (LogUtils.DEBUG) {LogUtils.v(imageDirPath + " 文件夹创建isOk" + isOk);}}final String audioDirPath = cacheDir + FileConstants.CACHE_AUDIO_DIR;final File audioFileDir = new File(audioDirPath);if (!audioFileDir.exists()) {boolean isOk = audioFileDir.mkdirs();if (LogUtils.DEBUG) {LogUtils.v(audioDirPath + " 文件夹创建isOk" + isOk);}}final String messageDirPath = cacheDir + FileConstants.CACHE_MESSAGE_DIR;final File messageFileDir = new File(messageDirPath);if (!messageFileDir.exists()) {boolean isOk = messageFileDir.mkdirs();if (LogUtils.DEBUG) {LogUtils.v(imageDirPath + " 文件夹创建isOk" + isOk);}}
}/*** 读取文件** @param sFileName* @return*/
public static String readFile(String sFileName) {if (TextUtils.isEmpty(sFileName)) {return null;}final StringBuffer sDest = new StringBuffer();final File f = new File(sFileName);if (!f.exists()) {return null;}try {FileInputStream is = new FileInputStream(f);BufferedReader br = new BufferedReader(new InputStreamReader(is));try {String data = null;while ((data = br.readLine()) != null) {sDest.append(data);}} catch (IOException ioex) {if (LogUtils.DEBUG) {LogUtils.e(ioex);}} finally {is.close();is = null;br.close();br = null;}} catch (Exception ex) {if (LogUtils.DEBUG) {LogUtils.e(ex);}} catch (OutOfMemoryError ex) {if (LogUtils.DEBUG) {ex.printStackTrace();}}return sDest.toString().trim();
}/*** 从assets 文件夹中获取文件并读取数据** @param context* @param fileName* @param isEncoding* @return*/
public static String getFromAssets(Context context, String fileName ) {String result = "";try {final InputStream in = context.getResources().getAssets().open(fileName);// 获取文件的字节数final int lenght = in.available();// 创建byte数组byte[] buffer = new byte[lenght];// 将文件中的数据读到byte数组中in.read(buffer);result = EncodingUtils.getString(buffer, "UTF-8");in.close();buffer = null;} catch(FileNotFoundException e) {e.printStackTrace();} catch (Exception e) {if (LogUtils.DEBUG) {LogUtils.e(e);}}return result;
}/*** 保存文件** @param sToSave* @param sFileName* @param isAppend* @return*/
public static boolean writeStringToFile(String content, String fileName, boolean isAppend) {return writeStringToFile(content, "", fileName, isAppend);
}public static boolean writeStringToFile(String content,String directoryPath, String fileName, boolean isAppend) {if (!TextUtils.isEmpty(content)) {if (!TextUtils.isEmpty(directoryPath)) {// 是否需要创建新的目录final File threadListFile = new File(directoryPath);if (!threadListFile.exists()) {threadListFile.mkdirs();}}boolean bFlag = false;final int iLen = content.length();final File file = new File(fileName);try {if (!file.exists()) {file.createNewFile();}final FileOutputStream fos = new FileOutputStream(file,isAppend);byte[] buffer = new byte[iLen];try {buffer = content.getBytes();fos.write(buffer);if (isAppend) {fos.write("||".getBytes());}fos.flush();bFlag = true;} catch (IOException ioex) {if (LogUtils.DEBUG) {LogUtils.e(ioex);}} finally {fos.close();buffer = null;}} catch (Exception ex) {if (LogUtils.DEBUG) {LogUtils.e(ex);}} catch (OutOfMemoryError o) {if (LogUtils.DEBUG) {o.printStackTrace();}}return bFlag;}return false;
}/*** 重命名** @param filePath* @return*/
public static boolean rename(String filePath, String newFilePath) {if (LogUtils.DEBUG) {LogUtils.e("filePath " + filePath);LogUtils.e("newFilePath " + newFilePath);}if (!TextUtils.isEmpty(filePath)) {final File file = new File(filePath);final File newFile = new File(newFilePath);if (file.exists()) {return file.renameTo(newFile);}}return false;
}   /*** 删除文件** @param filePath* @return*/
public static boolean deleteFile(String filePath) {if (LogUtils.DEBUG) {LogUtils.e("deleteFile path " + filePath);}if (!TextUtils.isEmpty(filePath)) {final File file = new File(filePath);if (LogUtils.DEBUG) {LogUtils.e("deleteFile path exists " + file.exists());}if (file.exists()) {return file.delete();}}return false;
}/*** 删除文件夹下所有文件** @return*/
public static void deleteDirectoryAllFile(String directoryPath) {final File file = new File(directoryPath);deleteDirectoryAllFile(file);
}public static void deleteDirectoryAllFile(File file) {if (!file.exists()) {return;}boolean rslt = true;// 保存中间结果if (!(rslt = file.delete())) {// 先尝试直接删除// 若文件夹非空。枚举、递归删除里面内容final File subs[] = file.listFiles();final int size = subs.length - 1;for (int i = 0; i <= size; i++) {if (subs[i].isDirectory())deleteDirectoryAllFile(subs[i]);// 递归删除子文件夹内容rslt = subs[i].delete();// 删除子文件夹本身}// rslt = file.delete();// 删除此文件夹本身}if (!rslt) {if (LogUtils.DEBUG) {LogUtils.w("无法删除:" + file.getName());}return;}
}/*** 根据后缀名删除文件** @param delpath*            path of file* @param delEndName*            end name of file* @return boolean the result*/
public static boolean deleteEndFile(String delPath, String delEndName) {// param is nullif (delPath == null || delEndName == null) {return false;}try {// create filefinal File file = new File(delPath);if (file != null) {if (file.isDirectory()) {// file listString[] fileList = file.list();File delFile = null;// diguifinal int size = fileList.length;for (int i = 0; i < size; i++) {// create new filedelFile = new File(delPath + "/" + fileList[i]);if (delFile != null && delFile.isFile()) {// 删除该文件夹下所有文件以delEndName为后缀的文件(不包含子文件夹里的文件)// if (delFile != null) {//// 删除该文件夹下所有文件以delEndName为后缀的文件(包含子文件夹里的文件)deleteEndFile(delFile.toString(), delEndName);} else {// nothing}}} else if (file.isFile()) {// check the end nameif (file.toString().contains(".")&& file.toString().substring((file.toString().lastIndexOf(".") + 1)).equals(delEndName)) {// file deletefile.delete();}}}} catch (Exception ex) {if (LogUtils.DEBUG) {LogUtils.e(ex);}return false;}return true;
}/*** 删除文件夹内所有文件** @param delpath*            delpath path of file* @return boolean the result*/
public static boolean deleteAllFile(String delpath) {try {// create filefinal File file = new File(delpath);if (!file.isDirectory()) {file.delete();} else if (file.isDirectory()) {final String[] filelist = file.list();final int size = filelist.length;for (int i = 0; i < size; i++) {// create new filefinal File delfile = new File(delpath + "/" + filelist[i]);if (!delfile.isDirectory()) {delfile.delete();} else if (delfile.isDirectory()) {// diguideleteFile(delpath + "/" + filelist[i]);}}file.delete();}} catch (Exception ex) {if (LogUtils.DEBUG) {LogUtils.e(ex);}return false;}return true;
}/*** 删除目录(文件夹)以及目录下的文件** @param sPath*            被删除目录的文件路径* @return 目录删除成功返回true,否则返回false*/
public static boolean deleteDirectory(String sPath) {if (TextUtils.isEmpty(sPath)) {return false;}boolean flag;// 如果sPath不以文件分隔符结尾,自动添加文件分隔符if (!sPath.endsWith(File.separator)) {sPath = sPath + File.separator;}final File dirFile = new File(sPath);// 如果dir对应的文件不存在,或者不是一个目录,则退出if (!dirFile.exists() || !dirFile.isDirectory()) {return false;}flag = true;// 删除文件夹下的所有文件(包括子目录)final File[] files = dirFile.listFiles();if (files != null && files.length > 0) {for (int i = 0; i < files.length; i++) {// 删除子文件if (files[i].isFile()) {flag = deleteFile(files[i].getAbsolutePath());if (!flag)break;} // 删除子目录else {flag = deleteDirectory(files[i].getAbsolutePath());if (!flag)break;}}}if (!flag)return false;// 删除当前目录if (dirFile.delete()) {return true;} else {return false;}
}/*** 获取后缀名** @param path*            全路径* @return*/
public static String getFileExtName(String path) {String ext = "";if ((path != null) && (path.length() > 0)) {int dot = path.lastIndexOf('.');if ((dot > -1) && (dot < (path.length() - 1))) {ext = path.substring(dot + 1);}}return ext;
}/*** 获取文件名** @param path*            全路径* @return*/
public static String getFileName(String path) {if (!TextUtils.isEmpty(path)) {return path.substring(path.lastIndexOf(File.separator) + 1);}return "";
}/*** 获取文件所在的文件路径** @param path* @return*/
public static String getFilePath(String path) {return path.substring(0, path.lastIndexOf(File.separator) + 1);
}/*** 复制文件** @param srcPath : 源文件全路径* @param destPath : 目标文件全路径* @return*/
public static long copyFile(String srcPath, String destPath) {try {int position = destPath.lastIndexOf(File.separator);String dir = destPath.substring(0, position);String newFileName = destPath.substring(position+1);final File cacheDir = new File(dir);if (!cacheDir.exists()) {cacheDir.mkdirs();}return copyFile(new File(srcPath), new File(dir), newFileName);} catch (Exception e) {return 0;}}/*** 复制文件(以超快的速度复制文件)** @param srcFile*            源文件File* @param destDir*            目标目录File* @param newFileName*            新文件名* @return 实际复制的字节数,如果文件、目录不存在、文件为null或者发生IO异常,返回-1*/
@SuppressWarnings("resource")
public static long copyFile(final File srcFile, final File destDir, String newFileName) {long copySizes = 0;if (!srcFile.exists()) {if (LogUtils.DEBUG) {LogUtils.d("源文件不存在");}copySizes = -1;} else if (!destDir.exists()) {if (LogUtils.DEBUG) {LogUtils.d("目标目录不存在");}copySizes = -1;} else if (newFileName == null) {if (LogUtils.DEBUG) {LogUtils.d("文件名为null");}copySizes = -1;} else {FileChannel fcin = null;FileChannel fcout = null;try {fcin = new FileInputStream(srcFile).getChannel();fcout = new FileOutputStream(new File(destDir, newFileName)).getChannel();long size = fcin.size();fcin.transferTo(0, fcin.size(), fcout);copySizes = size;} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally {try {if (fcin != null) {fcin.close();}if (fcout != null) {fcout.close();}} catch (IOException e) {e.printStackTrace();}}}return copySizes;
}/*** 判断asset下是否存在某个文件** @param context* @param fileName*            如:aa.txt或image/aa.jpg* @return*/
public static boolean existInAsset(Context context, String fileName) {boolean exist = false;try {String[] u = context.getAssets().list(getFilePath(fileName));for (String item : u) {if (item.equals(getFileName(fileName))) {exist = true;break;}}} catch (IOException e) {e.printStackTrace();}return exist;
}/*** 获取目录文件个数** @param f* @return*/
public static long getlist(File f) {long size = 0;try {File flist[] = f.listFiles();size = flist.length;for (int i = 0; i < flist.length; i++) {final File file = flist[i];if (file == null) {continue;}if (file.isDirectory()) {size = size + getlist(file);size--;}}} catch (Exception e) {e.printStackTrace();}return size;
}/*** 获取文件夹下所有文件大小** @param f* @return*/
public static long getFileSize(File f) {long size = 0;try {File flist[] = f.listFiles();for (int i = 0; i < flist.length; i++) {final File file = flist[i];if (file == null) {continue;}if (file.isDirectory()) {size = size + getFileSize(file);} else {size = size + file.length();}}} catch (Exception e) {e.printStackTrace();}return size;
}/*** 调用此方法自动计算指定文件或指定文件夹的大小** @param filePath 文件路径* @return 计算好的带B、KB、MB、GB的字符串*/
public static String getAutoFileOrFilesSize(File file) {if (file == null) {return "0B";}final long blockSize = getFileSize(file);if (LogUtils.DEBUG) {LogUtils.d("getAutoFileOrFilesSize 文件大小:" + blockSize);}return FormetFileSize(blockSize);
}/*** 转换文件大小* @param fileS* @return*/
private static String FormetFileSize(long fileS) {final 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 strcontent*/
public static void writeFileSdcard(String strcontent) {SimpleDateFormat formatter = new SimpleDateFormat("yyyy年MM月dd日   HH:mm:ss");Date curDate = new Date(System.currentTimeMillis());// 获取当前时间String str = formatter.format(curDate);// 每次写入时,都换行写String strContent = "-------当前时间===" + str + "\r\n" + strcontent + "\r\n";try {String strFilePath = Environment.getExternalStorageDirectory() + "/lunxun.text";File file = new File(strFilePath);if (!file.exists()) {Log.d("TestFile", "Create the file:" + strFilePath);file.createNewFile();}RandomAccessFile raf = new RandomAccessFile(file, "rw");raf.seek(file.length());raf.write(strContent.getBytes());raf.close();} catch (Exception e) {Log.e("TestFile", "Error on write File.");}
}

}

这篇关于你想要的这都有-Android文件工具类FileUtils的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1020441

相关文章

Python办公自动化实战之打造智能邮件发送工具

《Python办公自动化实战之打造智能邮件发送工具》在数字化办公场景中,邮件自动化是提升工作效率的关键技能,本文将演示如何使用Python的smtplib和email库构建一个支持图文混排,多附件,多... 目录前言一、基础配置:搭建邮件发送框架1.1 邮箱服务准备1.2 核心库导入1.3 基础发送函数二、

Android kotlin中 Channel 和 Flow 的区别和选择使用场景分析

《Androidkotlin中Channel和Flow的区别和选择使用场景分析》Kotlin协程中,Flow是冷数据流,按需触发,适合响应式数据处理;Channel是热数据流,持续发送,支持... 目录一、基本概念界定FlowChannel二、核心特性对比数据生产触发条件生产与消费的关系背压处理机制生命周期

Android ClassLoader加载机制详解

《AndroidClassLoader加载机制详解》Android的ClassLoader负责加载.dex文件,基于双亲委派模型,支持热修复和插件化,需注意类冲突、内存泄漏和兼容性问题,本文给大家介... 目录一、ClassLoader概述1.1 类加载的基本概念1.2 android与Java Class

基于Python实现一个图片拆分工具

《基于Python实现一个图片拆分工具》这篇文章主要为大家详细介绍了如何基于Python实现一个图片拆分工具,可以根据需要的行数和列数进行拆分,感兴趣的小伙伴可以跟随小编一起学习一下... 简单介绍先自己选择输入的图片,默认是输出到项目文件夹中,可以自己选择其他的文件夹,选择需要拆分的行数和列数,可以通过

Python使用pip工具实现包自动更新的多种方法

《Python使用pip工具实现包自动更新的多种方法》本文深入探讨了使用Python的pip工具实现包自动更新的各种方法和技术,我们将从基础概念开始,逐步介绍手动更新方法、自动化脚本编写、结合CI/C... 目录1. 背景介绍1.1 目的和范围1.2 预期读者1.3 文档结构概述1.4 术语表1.4.1 核

Python使用OpenCV实现获取视频时长的小工具

《Python使用OpenCV实现获取视频时长的小工具》在处理视频数据时,获取视频的时长是一项常见且基础的需求,本文将详细介绍如何使用Python和OpenCV获取视频时长,并对每一行代码进行深入解析... 目录一、代码实现二、代码解析1. 导入 OpenCV 库2. 定义获取视频时长的函数3. 打开视频文

Linux中压缩、网络传输与系统监控工具的使用完整指南

《Linux中压缩、网络传输与系统监控工具的使用完整指南》在Linux系统管理中,压缩与传输工具是数据备份和远程协作的桥梁,而系统监控工具则是保障服务器稳定运行的眼睛,下面小编就来和大家详细介绍一下它... 目录引言一、压缩与解压:数据存储与传输的优化核心1. zip/unzip:通用压缩格式的便捷操作2.

sqlite3 命令行工具使用指南

《sqlite3命令行工具使用指南》本文系统介绍sqlite3CLI的启动、数据库操作、元数据查询、数据导入导出及输出格式化命令,涵盖文件管理、备份恢复、性能统计等实用功能,并说明命令分类、SQL语... 目录一、启动与退出二、数据库与文件操作三、元数据查询四、数据操作与导入导出五、查询输出格式化六、实用功

Android DataBinding 与 MVVM使用详解

《AndroidDataBinding与MVVM使用详解》本文介绍AndroidDataBinding库,其通过绑定UI组件与数据源实现自动更新,支持双向绑定和逻辑运算,减少模板代码,结合MV... 目录一、DataBinding 核心概念二、配置与基础使用1. 启用 DataBinding 2. 基础布局

Android ViewBinding使用流程

《AndroidViewBinding使用流程》AndroidViewBinding是Jetpack组件,替代findViewById,提供类型安全、空安全和编译时检查,代码简洁且性能优化,相比Da... 目录一、核心概念二、ViewBinding优点三、使用流程1. 启用 ViewBinding (模块级