Android文件操作工具類詳解
本文實(shí)例為大家分享了Android文件操作工具類的具體代碼,供大家參考,具體內(nèi)容如下
貼上我寫的一個(gè)文件操作工具類,基本上覆蓋了各種文件操作:
1、文件的新建、刪除;
2、文件的復(fù)制;
3、獲取文件擴(kuò)展名;
4、文件的重命名;
5、獲取某個(gè)文件的詳細(xì)信息;
6、計(jì)算某個(gè)文件的大?。?/p>
7、文件大小的格式化;
8、獲取某個(gè)路徑下的文件列表;
9、獲取某個(gè)目錄下的文件列表;
10、目錄的新建、刪除;
11、目錄的復(fù)制;
12、計(jì)算某個(gè)目錄包含的文件數(shù)量;
13、計(jì)算某個(gè)目錄包含的文件大小;
代碼如下:
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", "application/octet-stream" }, { ".conf", "text/plain" }, { ".cpp", "text/plain" },
{ ".doc", "application/msword" },
{ ".docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document" },
{ ".xls", "application/vnd.ms-excel" },
{ ".xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" },
{ ".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/vnd.mpegurl" }, { ".m4v", "video/x-m4v" }, { ".mov", "video/quicktime" },
{ ".mp2", "audio/x-mpeg" }, { ".mp3", "audio/x-mpeg" }, { ".mp4", "video/mp4" },
{ ".mpc", "application/vnd.mpohun.certificate" }, { ".mpe", "video/mpeg" },
{ ".mpeg", "video/mpeg" }, { ".mpg", "video/mpeg" }, { ".mpg4", "video/mp4" },
{ ".mpga", "audio/mpeg" }, { ".msg", "application/vnd.ms-outlook" }, { ".ogg", "audio/ogg" },
{ ".pdf", "application/pdf" }, { ".png", "image/png" },
{ ".pps", "application/vnd.ms-powerpoint" }, { ".ppt", "application/vnd.ms-powerpoint" },
{ ".pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation" },
{ ".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/vnd.ms-works" }, { ".xml", "text/plain" },
{ ".z", "application/x-compress" }, { ".zip", "application/x-zip-compressed" }, { "", "*/*" }
};
/**
* 根據(jù)文件后綴名獲得對應(yīng)的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和文件類型的匹配表中找到對應(yīng)的MIME類型
for (int i = 0; i < MIME_MapTable.length; i++)
{
if (end.equals(MIME_MapTable[i][0]))
{
type = MIME_MapTable[i][1];
}
}
return type;
}
/**
* 創(chuàng)建文件
*
* @param path
* 文件所在目錄的目錄名,如/java/test/0.txt,要在當(dāng)前目錄下創(chuàng)建一個(gè)文件名為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;
}
/**
* 刪除單個(gè)文件
*
* @param file
* 要刪除的文件對象
* @return 文件刪除成功則返回true
*/
public static boolean deleteFile(File file)
{
if (file.exists())
{
boolean isDeleted = file.delete();
Log.w(Util.TAG, file.getName() + "刪除結(jié)果:" + isDeleted);
return isDeleted;
}
else
{
Log.w(Util.TAG, "文件刪除失?。何募淮嬖冢?);
return false;
}
}
/**
* 刪除單個(gè)文件
*
* @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;
}
}
/**
* 復(fù)制文件
*
* @param srcPath
* 源文件絕對路徑
* @param destDir
* 目標(biāo)文件所在目錄
* @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;
}
// 獲取待復(fù)制文件的文件名
String fileName = srcPath.substring(srcPath.lastIndexOf(File.separator));
String destPath = destDir + fileName;
if (destPath.equals(srcPath))
{
// 源文件路徑和目標(biāo)文件路徑重復(fù)
Util.toast("源文件路徑和目標(biāo)文件路徑重復(fù)!");
return false;
}
File destFile = new File(destPath); // 目標(biāo)文件
if (destFile.exists() && destFile.isFile())
{
// 該路徑下已經(jīng)有一個(gè)同名文件
Util.toast("目標(biāo)目錄下已有同名文件!");
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, 0, c);
}
fis.close();
fos.close();
flag = true;
}
catch (IOException e)
{
e.printStackTrace();
}
if (flag)
{
Util.toast("復(fù)制文件成功!");
}
return flag;
}
/**
* 根據(jù)文件名獲得文件的擴(kuò)展名
*
* @param fileName
* 文件名
* @return 文件擴(kuò)展名(不帶點(diǎn))
*/
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, "文件重命名失?。盒屡f文件名絕對路徑相同!");
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, "文件重命名失?。号f文件對象和新文件對象相同!");
return false;
}
boolean isSuccess = oldFile.renameTo(newFile);
Log.w(Util.TAG, "文件重命名是否成功:" + isSuccess);
return isSuccess;
}
/**
* 重命名文件
*
* @param oldFile
* 舊文件對象,F(xiàn)ile類型
* @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;
}
/**
* 計(jì)算某個(gè)文件的大小
*
* @param file
* 文件對象
* @return 文件大小,如果file不是文件,則返回-1
*/
public static long getFileSize(File file)
{
if (file.isFile())
{
return file.length();
}
else
{
return -1;
}
}
/**
* 計(jì)算某個(gè)文件的大小
*
* @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";
}
}
/**
* 格式化文件最后修改時(shí)間字符串
*
* @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;
}
/**
* 獲取某個(gè)路徑下的文件列表
*
* @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;
}
}
/**
* 獲取某個(gè)目錄下的文件列表
*
* @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 創(chuàng)建成功則返回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;
}
}
/**
* 復(fù)制目錄
*
* @param srcPath
* 源文件夾路徑
* @param destPath
* 目標(biāo)文件夾所在目錄
* @return 復(fù)制成功則返回true
*/
public static boolean copyFolder(String srcPath, String destDir)
{
Util.toast("復(fù)制文件夾開始!");
boolean flag = false;
File srcFile = new File(srcPath);
if (!srcFile.exists())
{
// 源文件夾不存在
Util.toast("源文件夾不存在");
return false;
}
String dirName = getDirName(srcPath); // 獲得待復(fù)制的文件夾的名字,比如待復(fù)制的文件夾為"E://dir"則獲取的名字為"dir"
String destPath = destDir + File.separator + dirName; // 目標(biāo)文件夾的完整路徑
// Util.toast("目標(biāo)文件夾的完整路徑為:" + destPath);
if (destPath.equals(srcPath))
{
Util.toast("目標(biāo)文件夾與源文件夾重復(fù)");
return false;
}
File destDirFile = new File(destPath);
if (destDirFile.exists())
{
// 目標(biāo)位置有一個(gè)同名文件夾
Util.toast("目標(biāo)位置已有同名文件夾!");
return false;
}
destDirFile.mkdirs(); // 生成目錄
File[] files = srcFile.listFiles(); // 獲取源文件夾下的子文件和子文件夾
if (files.length == 0)
{
// 如果源文件夾為空目錄則直接設(shè)置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("復(fù)制文件夾成功!");
}
return flag;
}
/**
* 獲取待復(fù)制文件夾的文件夾名
*
* @param dir
* @return String
*/
public static String getDirName(String dir)
{
if (dir.endsWith(File.separator))
{
// 如果文件夾路徑以"http://"結(jié)尾,則先去除末尾的"http://"
dir = dir.substring(0, dir.lastIndexOf(File.separator));
}
return dir.substring(dir.lastIndexOf(File.separator) + 1);
}
/**
* 計(jì)算某個(gè)目錄包含的文件數(shù)量
*
* @param directory
* @return
*/
public static int getFileCount(File directory)
{
File[] files = directory.listFiles();
int count = files.length;
return count;
}
/**
* 計(jì)算某個(gè)路徑下所包含的文件數(shù)量
*
* @param path
* @return
*/
public static int getFileCount(String path)
{
File file = new File(path);
File[] files = file.listFiles();
int count = files.length;
return count;
}
/**
* 計(jì)算某個(gè)目錄的大小
*
* @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;
}
/**
* 獲得某個(gè)文件或目錄的大小
*
* @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平臺系統(tǒng)下測試過,基本上沒問題,如果你碰到什么問題,可以在評論里給我留言,歡迎斧正!
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Android自定義View實(shí)現(xiàn)縱向跑馬燈效果詳解
對于跑馬燈效果在我們?nèi)粘J褂玫腶pp中還是很常見的,比如外賣app的商家公告就使用了此效果,但是它是橫向滾動的,橫向滾動多適用于單條信息;但凡涉及到多條信息的滾動展示,用縱向滾動效果會有更好的用戶體驗(yàn),今天我們通過自定義View來看看如何實(shí)現(xiàn)縱向跑馬燈效果。2016-11-11
Android?利用ImageView屬性實(shí)現(xiàn)選中和未選中效果
這篇文章主要介紹了Android巧用ImageView屬性實(shí)現(xiàn)選中和未選中效果,實(shí)現(xiàn)思路通常我們會選擇在布局里加個(gè)ImageView,然后通過代碼層面加個(gè)判斷去讓ImageView加載不同狀態(tài)的圖片,需要的朋友可以參考下2023-06-06
Android使用RecycleView實(shí)現(xiàn)拖拽交換item位置
這篇文章主要為大家詳細(xì)介紹了Android使用RecycleView實(shí)現(xiàn)拖拽交換item位置,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-08-08
Android Studio使用ViewPager+Fragment實(shí)現(xiàn)滑動菜單Tab效果
這篇文章主要為大家詳細(xì)介紹了Android Studio使用ViewPager+Fragment實(shí)現(xiàn)滑動菜單Tab效果,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-09-09
Android底部菜單欄(RadioGroup+Fragment)美化
這篇文章主要介紹了Android底部菜單欄RadioGroup+Fragment美化,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2020-07-07
Android實(shí)現(xiàn)可瀏覽和搜索的聯(lián)系人列表
這篇文章主要為大家詳細(xì)介紹了Android實(shí)現(xiàn)可瀏覽和搜索的聯(lián)系人列表的相關(guān)代碼,瀏覽所有聯(lián)系人和根據(jù)名稱搜索聯(lián)系人,感興趣的小伙伴們可以參考一下2016-07-07
Android編程實(shí)現(xiàn)動態(tài)更新ListView的方法
這篇文章主要介紹了Android編程實(shí)現(xiàn)動態(tài)更新ListView的方法,結(jié)合實(shí)例形式詳細(xì)分析了ListView的布局及動態(tài)更新實(shí)現(xiàn)方法,需要的朋友可以參考下2016-02-02

