This article shares the specific code of Android file operation tool for your reference. The specific content is as follows
I posted a file operation tool class I wrote, which basically covers various file operations:
1. New creation and deletion of files;
2. Copying of files;
3. Get the file extension;
4. Rename the file;
5. Obtain detailed information of a file;
6. Calculate the size of a certain file;
7. Format of file size;
8. Get the file list under a certain path;
9. Get the file list in a certain directory;
10. Create or delete the directory;
11. Copying of directories;
12. Calculate the number of files contained in a certain directory;
13. Calculate the file size contained in a certain directory;
The code is as follows:
1、
package ; import ; import ; import ; import ; import ; import ; import ; import ; import ; import ; import ; import ; import ; public class FileUtil { private static final String[][] MIME_MapTable = { // {suffix name, MIME type} { ".3gp", "video/3gpp" }, { ".apk", "application/-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/" }, { ".xls", "application/-excel" }, { ".xlsx", "application/" }, { ".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/" }, { ".m4v", "video/x-m4v" }, { ".mov", "video/quicktime" }, { ".mp2", "audio/x-mpeg" }, { ".mp3", "audio/x-mpeg" }, { ".mp4", "video/mp4" }, { ".mpc", "application/" }, { ".mpe", "video/mpeg" }, { ".mpeg", "video/mpeg" }, { ".mpg", "video/mpeg" }, { ".mpg4", "video/mp4" }, { ".mpga", "audio/mpeg" }, { ".msg", "application/-outlook" }, { ".ogg", "audio/ogg" }, { ".pdf", "application/pdf" }, { ".png", "image/png" }, { ".pps", "application/-powerpoint" }, { ".ppt", "application/-powerpoint" }, { ".pptx", "application/" }, { ".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/-works" }, { ".xml", "text/plain" }, { ".z", "application/x-compress" }, { ".zip", "application/x-zip-compressed" }, { "", "*/*" } }; /** * Obtain the corresponding MIME type according to the file suffix name * * @param file * File object */ public static String getMIMEType(File file) { String type = "*/*"; String fileName = (); int dotIndex = ("."); // Get the position of the delimiter "." before the suffix name in fileName if (dotIndex < 0) { return type; } String end = (dotIndex, ()).toLowerCase(()); // Get the file's suffix name if (() == 0) { return type; } // Find the corresponding MIME type in the matching table of MIME and file type for (int i = 0; i < MIME_MapTable.length; i++) { if ((MIME_MapTable[i][0])) { type = MIME_MapTable[i][1]; } } return type; } /** * Create a file * * @param path * The directory name of the directory where the file is located, such as /java/test/, you want to create a file with the file name in the current directory, <br> * Then the path is /java/test, fileName is * @param fileName * file name * @return If the file is created successfully, it will return true. */ public static boolean createFile(String path, String fileName) { File file = new File(path + + fileName); if (()) { (, "New file creation failed:()=" + ()); return false; } else { try { boolean isCreated = (); return isCreated; } catch (IOException e) { (); } } return false; } /** * Delete a single file * * @param file * File object to delete * @return If the file is deleted successfully, it will return true. */ public static boolean deleteFile(File file) { if (()) { boolean isDeleted = (); (, () + "Delete result:" + isDeleted); return isDeleted; } else { (, "File deletion failed: the file does not exist!"); return false; } } /** * Delete a single file * * @param path * The path name of the file * @param fileName * file name * @return If the delete is successful, it will return true. */ public static boolean deleteFile(String path, String fileName) { File file = new File(path + + fileName); if (()) { boolean isDeleted = (); return isDeleted; } else { return false; } } /** * Copy the file * * @param srcPath * Absolute path to the source file * @param destDir * The directory where the target file is located * @return boolean */ public static boolean copyFile(String srcPath, String destDir) { boolean flag = false; File srcFile = new File(srcPath); // Source file if (!()) { // The source file does not exist ("The source file does not exist"); return false; } // Get the file name of the file to be copied String fileName = (()); String destPath = destDir + fileName; if ((srcPath)) { // The source file path and the target file path are repeated ("The source file path and the target file path are repeated!"); return false; } File destFile = new File(destPath); // Target file if (() && ()) { // There is already a file with the same name under this path ("The file with the same name is already in the target directory!"); return false; } File destFileDir = new File(destDir); (); try { FileInputStream fis = new FileInputStream(srcPath); FileOutputStream fos = new FileOutputStream(destFile); byte[] buf = new byte[1024]; int c; while ((c = (buf)) != -1) { (buf, 0, c); } (); (); flag = true; } catch (IOException e) { (); } if (flag) { ("The file was copied successfully!"); } return flag; } /** * Obtain the file extension based on the file name * * @param fileName * file name * @return File extension (without dots) */ public static String getFileSuffix(String fileName) { int index = ("."); String suffix = (index + 1, ()); return suffix; } /** * Rename the file * * @param oldPath * Absolute path to old files * @param newPath * Absolute path to new file * @return If the file rename is successful, it will return true. */ public static boolean renameTo(String oldPath, String newPath) { if ((newPath)) { (, "File renaming failed: the paths of the old and new file names are absolutely the same!"); return false; } File oldFile = new File(oldPath); File newFile = new File(newPath); boolean isSuccess = (newFile); (, "Whether the file renaming is successful:" + isSuccess); return isSuccess; } /** * Rename the file * * @param oldFile * Old file object * @param newFile * New file object * @return If the file rename is successful, it will return true. */ public static boolean renameTo(File oldFile, File newFile) { if ((newFile)) { (, "File renaming failed: the old file object is the same as the new file object!"); return false; } boolean isSuccess = (newFile); (, "Whether the file renaming is successful:" + isSuccess); return isSuccess; } /** * Rename the file * * @param oldFile * Old file object, File type * @param newName * File name of the new file, String type * @return If the rename is successful, it will return true */ public static boolean renameTo(File oldFile, String newName) { File newFile = new File(() + + newName); boolean flag = (newFile); (flag); return flag; } /** * Calculate the size of a file * * @param file * File object * @return File size, if file is not a file, return -1 */ public static long getFileSize(File file) { if (()) { return (); } else { return -1; } } /** * Calculate the size of a file * * @param path * Absolute path to the file * @return */ public static long getFileSize(String path) { File file = new File(path); long size = (); return size; } /** * Format of file size * * @param size * File size, unit is byte * @return File size formatted text */ public static String formatSize(long size) { DecimalFormat df = new DecimalFormat("####.00"); if (size < 1024) // Less than 1KB { return size + "Byte"; } else if (size < 1024 * 1024) // Less than 1MB { float kSize = size / 1024f; return (kSize) + "KB"; } else if (size < 1024 * 1024 * 1024) // Less than 1GB { float mSize = size / 1024f / 1024f; return (mSize) + "MB"; } else if (size < 1024L * 1024L * 1024L * 1024L) // Less than 1TB { float gSize = size / 1024f / 1024f / 1024f; return (gSize) + "GB"; } else { return "size: error"; } } /** * The last time string to format the file * * @param time * @return */ public static String formatTime(long time) { Date date = new Date(time); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd,HH:mm:ss", ()); String formatedTime = (date); return formatedTime; } /** * Get the list of files under a certain path * * @param path * File path * @return File list File[] files */ public static File[] getFileList(String path) { File file = new File(path); if (()) { File[] files = (); if (files != null) { return files; } else { return null; } } else { return null; } } /** * Get the list of files in a directory * * @param directory * Table of contents * @return File list File[] files */ public static File[] getFileList(File directory) { File[] files = (); if (files != null) { return files; } else { return null; } } /** * Get the root directory file list * * @param showHidden * @param object * @param showHidden * Whether to display hidden files * @return */ public static List<File> getSDCardFileList(boolean showHidden) { List<File> list = new ArrayList<>(); File files[]; if (().equals(Environment.MEDIA_MOUNTED)) { File extDir = (); files = (); for (File file : files) { (file); } if (showHidden) { // } else { for (int i = 0; i < (); i++) { File file = (i); if (() || ().startsWith(".")) { (file); } } } } else { ("SD card is not mounted!"); } return list; } /** * Create a new directory * * @param path * Absolute path to the directory * @return Return true if created successfully */ public static boolean createFolder(String path) { File file = new File(path); boolean isCreated = (); return isCreated; } /** * Create a new directory * * @param file * @return */ public static boolean createFolder(File file) { boolean isCreated = (); return isCreated; } /** * Delete the folder and all files it contains * * @param file * @return */ public static boolean deleteFolder(File file) { boolean flag = false; File files[] = (); if (files != null && >= 0) // There is a file list in the directory { for (int i = 0; i < ; i++) { File f = files[i]; if (()) { // Delete subfiles flag = deleteFile(f); if (flag == false) { return flag; } } else { // Delete subdirectories flag = deleteFolder(f); if (flag == false) { return flag; } } } } flag = (); if (flag == false) { return flag; } else { return true; } } /** * Copy the directory * * @param srcPath * Source folder path * @param destPath * The directory where the target folder is located * @return Return true if copying is successful */ public static boolean copyFolder(String srcPath, String destDir) { ("Copy the folder to start!"); boolean flag = false; File srcFile = new File(srcPath); if (!()) { // The source folder does not exist ("The source folder does not exist"); return false; } String dirName = getDirName(srcPath); // Get the name of the folder to be copied. For example, if the folder to be copied is "E://dir", the name obtained is "dir" String destPath = destDir + + dirName; // The full path to the target folder // ("The full path to the destination folder is: " + destPath); if ((srcPath)) { ("Dull destination folder and source folder"); return false; } File destDirFile = new File(destPath); if (()) { // There is a folder with the same name at the destination location ("The target location already has a folder with the same name!"); return false; } (); // Generate directory File[] files = (); // Get subfiles and subfolders under the source folder if ( == 0) { // If the source folder is an empty directory, set flag to true directly. This step is very hidden and debugged for a long time. flag = true; } else { for (File temp : files) { if (()) { // document flag = copyFile((), destPath); } else if (()) { // Folder flag = copyFolder((), destPath); } if (!flag) { break; } } } if (flag) { ("Copy the folder successfully!"); } return flag; } /** * Get the folder name of the folder to be copied * * @param dir * @return String */ public static String getDirName(String dir) { if (()) { // If the folder path ends with "//", first remove the "//" at the end dir = (0, ()); } return (() + 1); } /** * Calculate the number of files contained in a directory * * @param directory * @return */ public static int getFileCount(File directory) { File[] files = (); int count = ; return count; } /** * Calculate the number of files contained in a certain path * * @param path * @return */ public static int getFileCount(String path) { File file = new File(path); File[] files = (); int count = ; return count; } /** * Calculate the size of a directory * * @param file * @return */ public static long getFolderSize(File directory) { File[] files = (); if (files != null && >= 0) { long size = 0; for (File f : files) { if (()) { // Get the size of the subfile size = size + getFileSize(f); } else { // Get the size of the subdirectory size = size + getFolderSize(f); } } return size; } return -1; } /** * Get the size of a file or directory * * @param file * @return */ public static long getFileOrFolderSize(File file) { long size = 0; if (()) { size = getFolderSize(file); } else { size = getFileSize(file); } return size; } }
All the above methods have been tested under the Windows platform system, and there is basically no problem. If you encounter any problems, you can leave me a message in the comments. Welcome to correct me!
The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.