Android檔案操作工具類詳解
阿新 • • 發佈:2020-07-17
本文例項為大家分享了Android檔案操作工具類的具體程式碼,供大家參考,具體內容如下
貼上我寫的一個檔案操作工具類,基本上覆蓋了各種檔案操作:
1、檔案的新建、刪除;
2、檔案的複製;
3、獲取副檔名;
4、檔案的重新命名;
5、獲取某個檔案的詳細資訊;
6、計算某個檔案的大小;
7、檔案大小的格式化;
8、獲取某個路徑下的檔案列表;
9、獲取某個目錄下的檔案列表;
10、目錄的新建、刪除;
11、目錄的複製;
12、計算某個目錄包含的檔案數量;
13、計算某個目錄包含的檔案大小;
程式碼如下:
1、FileUtil.java
package com.ctgu.filemaster.utils; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.text.DecimalFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.List; import java.util.Locale; import android.os.Environment; import android.util.Log; public class FileUtil { private static final 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",{ ".conf",{ ".cpp",{ ".doc","application/msword" },{ ".docx","application/vnd.openxmlformats-officedocument.wordprocessingml.document" },{ ".xls","application/vnd.ms-excel" },{ ".xlsx","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" },{ ".exe",{ ".gif","image/gif" },{ ".gtar","application/x-gtar" },{ ".gz","application/x-gzip" },{ ".h",{ ".htm","text/html" },{ ".html",{ ".jar","application/java-archive" },{ ".java",{ ".jpeg","image/jpeg" },{ ".jpg",{ ".js","application/x-javascript" },{ ".log",{ ".m3u","audio/x-mpegurl" },{ ".m4a","audio/mp4a-latm" },{ ".m4b",{ ".m4p",{ ".m4u","video/vnd.mpegurl" },{ ".m4v","video/x-m4v" },{ ".mov","video/quicktime" },{ ".mp2","audio/x-mpeg" },{ ".mp3",{ ".mp4","video/mp4" },{ ".mpc","application/vnd.mpohun.certificate" },{ ".mpe","video/mpeg" },{ ".mpeg",{ ".mpg",{ ".mpg4",{ ".mpga","audio/mpeg" },{ ".msg","application/vnd.ms-outlook" },{ ".ogg","audio/ogg" },{ ".pdf","application/pdf" },{ ".png","image/png" },{ ".pps","application/vnd.ms-powerpoint" },{ ".ppt",{ ".pptx","application/vnd.openxmlformats-officedocument.presentationml.presentation" },{ ".prop",{ ".rc",{ ".rmvb","audio/x-pn-realaudio" },{ ".rtf","application/rtf" },{ ".sh",{ ".tar","application/x-tar" },{ ".tgz","application/x-compressed" },{ ".txt",{ ".wav","audio/x-wav" },{ ".wma","audio/x-ms-wma" },{ ".wmv","audio/x-ms-wmv" },{ ".wps","application/vnd.ms-works" },{ ".xml",{ ".z","application/x-compress" },{ ".zip","application/x-zip-compressed" },{ "","*/*" } }; /** * 根據檔案字尾名獲得對應的MIME型別 * * @param file * 檔案物件 */ public static String getMIMEType(File file) { String type = "*/*"; String fileName = file.getName(); int dotIndex = fileName.lastIndexOf("."); // 獲取字尾名前的分隔符"."在fileName中的位置 if (dotIndex < 0) { return type; } String end = fileName.substring(dotIndex,fileName.length()).toLowerCase(Locale.getDefault()); // 獲取檔案的字尾名 if (end.length() == 0) { return type; } // 在MIME和檔案型別的匹配表中找到對應的MIME型別 for (int i = 0; i < MIME_MapTable.length; i++) { if (end.equals(MIME_MapTable[i][0])) { type = MIME_MapTable[i][1]; } } return type; } /** * 建立檔案 * * @param path * 檔案所在目錄的目錄名,如/java/test/0.txt,要在當前目錄下建立一個檔名為1.txt的檔案,<br> * 則path為/java/test,fileName為1.txt * @param fileName * 檔名 * @return 檔案新建成功則返回true */ public static boolean createFile(String path,String fileName) { File file = new File(path + File.separator + fileName); if (file.exists()) { Log.w(Util.TAG,"新建檔案失敗:file.exist()=" + file.exists()); return false; } else { try { boolean isCreated = file.createNewFile(); return isCreated; } catch (IOException e) { e.printStackTrace(); } } return false; } /** * 刪除單個檔案 * * @param file * 要刪除的檔案物件 * @return 檔案刪除成功則返回true */ public static boolean deleteFile(File file) { if (file.exists()) { boolean isDeleted = file.delete(); Log.w(Util.TAG,file.getName() + "刪除結果:" + isDeleted); return isDeleted; } else { Log.w(Util.TAG,"檔案刪除失敗:檔案不存在!"); return false; } } /** * 刪除單個檔案 * * @param path * 檔案所在路徑名 * @param fileName * 檔名 * @return 刪除成功則返回true */ public static boolean deleteFile(String path,String fileName) { File file = new File(path + File.separator + fileName); if (file.exists()) { boolean isDeleted = file.delete(); return isDeleted; } else { return false; } } /** * 複製檔案 * * @param srcPath * 原始檔絕對路徑 * @param destDir * 目標檔案所在目錄 * @return boolean */ public static boolean copyFile(String srcPath,String destDir) { boolean flag = false; File srcFile = new File(srcPath); // 原始檔 if (!srcFile.exists()) { // 原始檔不存在 Util.toast("原始檔不存在"); return false; } // 獲取待複製檔案的檔名 String fileName = srcPath.substring(srcPath.lastIndexOf(File.separator)); String destPath = destDir + fileName; if (destPath.equals(srcPath)) { // 原始檔路徑和目標檔案路徑重複 Util.toast("原始檔路徑和目標檔案路徑重複!"); return false; } File destFile = new File(destPath); // 目標檔案 if (destFile.exists() && destFile.isFile()) { // 該路徑下已經有一個同名檔案 Util.toast("目標目錄下已有同名檔案!"); return false; } File destFileDir = new File(destDir); destFileDir.mkdirs(); try { FileInputStream fis = new FileInputStream(srcPath); FileOutputStream fos = new FileOutputStream(destFile); byte[] buf = new byte[1024]; int c; while ((c = fis.read(buf)) != -1) { fos.write(buf,c); } fis.close(); fos.close(); flag = true; } catch (IOException e) { e.printStackTrace(); } if (flag) { Util.toast("複製檔案成功!"); } return flag; } /** * 根據檔名獲得檔案的副檔名 * * @param fileName * 檔名 * @return 副檔名(不帶點) */ public static String getFileSuffix(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(String oldPath,String newPath) { if (oldPath.equals(newPath)) { Log.w(Util.TAG,"檔案重新命名失敗:新舊檔名絕對路徑相同!"); return false; } File oldFile = new File(oldPath); File newFile = new File(newPath); boolean isSuccess = oldFile.renameTo(newFile); Log.w(Util.TAG,"檔案重新命名是否成功:" + isSuccess); return isSuccess; } /** * 重新命名檔案 * * @param oldFile * 舊檔案物件 * @param newFile * 新檔案物件 * @return 檔案重新命名成功則返回true */ public static boolean renameTo(File oldFile,File newFile) { if (oldFile.equals(newFile)) { Log.w(Util.TAG,"檔案重新命名失敗:舊檔案物件和新檔案物件相同!"); return false; } boolean isSuccess = oldFile.renameTo(newFile); Log.w(Util.TAG,"檔案重新命名是否成功:" + 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); System.out.println(flag); return flag; } /** * 計算某個檔案的大小 * * @param file * 檔案物件 * @return 檔案大小,如果file不是檔案,則返回-1 */ public static long getFileSize(File file) { if (file.isFile()) { return file.length(); } else { return -1; } } /** * 計算某個檔案的大小 * * @param path * 檔案的絕對路徑 * @return */ public static long getFileSize(String path) { File file = new File(path); long size = file.length(); return size; } /** * 檔案大小的格式化 * * @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 time * @return */ public static String formatTime(long time) { Date date = new Date(time); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd,HH:mm:ss",Locale.getDefault()); String formatedTime = sdf.format(date); return formatedTime; } /** * 獲取某個路徑下的檔案列表 * * @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; } } /** * 獲得根目錄檔案列表 * * @param showHidden * @param object * @param showHidden * 是否顯示隱藏檔案 * @return */ public static List<File> getSDCardFileList(boolean showHidden) { List<File> list = new ArrayList<>(); File files[]; if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { File extDir = Environment.getExternalStorageDirectory(); files = extDir.listFiles(); for (File file : files) { list.add(file); } if (showHidden) { // } else { for (int i = 0; i < list.size(); i++) { File file = list.get(i); if (file.isHidden() || file.getName().startsWith(".")) { list.remove(file); } } } } else { Util.toast("SD卡未掛載!"); } return list; } /** * 新建目錄 * * @param path * 目錄的絕對路徑 * @return 建立成功則返回true */ public static boolean createFolder(String path) { File file = new File(path); boolean isCreated = file.mkdir(); return isCreated; } /** * 新建目錄 * * @param file * @return */ public static boolean createFolder(File file) { boolean isCreated = file.mkdir(); return isCreated; } /** * 刪除資料夾及其包含的所有檔案 * * @param file * @return */ public static boolean deleteFolder(File file) { boolean flag = false; File files[] = file.listFiles(); if (files != null && files.length >= 0) // 目錄下存在檔案列表 { for (int i = 0; i < files.length; i++) { File f = files[i]; if (f.isFile()) { // 刪除子檔案 flag = deleteFile(f); if (flag == false) { return flag; } } else { // 刪除子目錄 flag = deleteFolder(f); if (flag == false) { return flag; } } } } flag = file.delete(); if (flag == false) { return flag; } else { return true; } } /** * 複製目錄 * * @param srcPath * 原始檔夾路徑 * @param destPath * 目標資料夾所在目錄 * @return 複製成功則返回true */ public static boolean copyFolder(String srcPath,String destDir) { Util.toast("複製資料夾開始!"); boolean flag = false; File srcFile = new File(srcPath); if (!srcFile.exists()) { // 原始檔夾不存在 Util.toast("原始檔夾不存在"); return false; } String dirName = getDirName(srcPath); // 獲得待複製的資料夾的名字,比如待複製的資料夾為"E://dir"則獲取的名字為"dir" String destPath = destDir + File.separator + dirName; // 目標資料夾的完整路徑 // Util.toast("目標資料夾的完整路徑為:" + destPath); if (destPath.equals(srcPath)) { Util.toast("目標資料夾與原始檔夾重複"); return false; } File destDirFile = new File(destPath); if (destDirFile.exists()) { // 目標位置有一個同名資料夾 Util.toast("目標位置已有同名資料夾!"); return false; } destDirFile.mkdirs(); // 生成目錄 File[] files = srcFile.listFiles(); // 獲取原始檔夾下的子檔案和子資料夾 if (files.length == 0) { // 如果原始檔夾為空目錄則直接設定flag為true,這一步非常隱蔽,debug了很久 flag = true; } else { for (File temp : files) { if (temp.isFile()) { // 檔案 flag = copyFile(temp.getAbsolutePath(),destPath); } else if (temp.isDirectory()) { // 資料夾 flag = copyFolder(temp.getAbsolutePath(),destPath); } if (!flag) { break; } } } if (flag) { Util.toast("複製資料夾成功!"); } return flag; } /** * 獲取待複製資料夾的資料夾名 * * @param dir * @return String */ public static String getDirName(String dir) { if (dir.endsWith(File.separator)) { // 如果資料夾路徑以"//"結尾,則先去除末尾的"//" dir = dir.substring(0,dir.lastIndexOf(File.separator)); } return dir.substring(dir.lastIndexOf(File.separator) + 1); } /** * 計算某個目錄包含的檔案數量 * * @param directory * @return */ public static int getFileCount(File directory) { File[] files = directory.listFiles(); int count = files.length; return count; } /** * 計算某個路徑下所包含的檔案數量 * * @param path * @return */ public static int getFileCount(String path) { File file = new File(path); File[] files = file.listFiles(); int count = files.length; return count; } /** * 計算某個目錄的大小 * * @param file * @return */ public static long getFolderSize(File directory) { File[] files = directory.listFiles(); if (files != null && files.length >= 0) { long size = 0; for (File f : files) { if (f.isFile()) { // 獲得子檔案的大小 size = size + getFileSize(f); } else { // 獲得子目錄的大小 size = size + getFolderSize(f); } } return size; } return -1; } /** * 獲得某個檔案或目錄的大小 * * @param file * @return */ public static long getFileOrFolderSize(File file) { long size = 0; if (file.isDirectory()) { size = getFolderSize(file); } else { size = getFileSize(file); } return size; } }
以上各方法均在Windows平臺系統下測試過,基本上沒問題,如果你碰到什麼問題,可以在評論裡給我留言,歡迎斧正!
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。