栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 移动开发 > Android

Android文件操作工具类详解

Android 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Android文件操作工具类详解

本文实例为大家分享了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", "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" }, { "", "*
  public static String getMIMEType(File file)
  {
    String type = "*
  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;
  }
 
  
  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;
    }
  }
 
  
  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;
    }
  }
 
  
  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, 0, c);
      }
      fis.close();
      fos.close();
 
      flag = true;
    }
    catch (IOException e)
    {
      e.printStackTrace();
    }
    if (flag)
    {
      Util.toast("复制文件成功!");
    }
    return flag;
  }
 
  
  public static String getFileSuffix(String fileName)
  {
    int index = fileName.lastIndexOf(".");
    String suffix = fileName.substring(index + 1, fileName.length());
    return suffix;
  }
 
  
  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;
  }
 
  
  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;
  }
 
  
  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;
  }
 
  
  public static long getFileSize(File file)
  {
    if (file.isFile())
    {
      return file.length();
    }
    else
    {
      return -1;
    }
  }
 
  
  public static long getFileSize(String path)
  {
    File file = new File(path);
    long size = file.length();
    return size;
  }
 
  
  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";
    }
  }
 
  
  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;
  }
 
  
  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;
    }
  }
 
  
  public static File[] getFileList(File directory)
  {
    File[] files = directory.listFiles();
    if (files != null)
    {
      return files;
    }
    else
    {
      return null;
    }
  }
 
  
  public static List getSDCardFileList(boolean showHidden)
  {
    List 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;
  }
 
  
  public static boolean createFolder(String path)
  {
    File file = new File(path);
    boolean isCreated = file.mkdir();
    return isCreated;
  }
 
  
  public static boolean createFolder(File file)
  {
    boolean isCreated = file.mkdir();
    return isCreated;
  }
 
  
  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;
    }
  }
 
  
  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;
  }
 
  
  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);
  }
 
  
  public static int getFileCount(File directory)
  {
    File[] files = directory.listFiles();
    int count = files.length;
    return count;
  }
 
  
  public static int getFileCount(String path)
  {
    File file = new File(path);
    File[] files = file.listFiles();
    int count = files.length;
    return count;
  }
 
  
  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;
  }
 
  
  public static long getFileOrFolderSize(File file)
  {
    long size = 0;
    if (file.isDirectory())
    {
      size = getFolderSize(file);
    }
    else
    {
      size = getFileSize(file);
    }
    return size;
  }
}

以上各方法均在Windows平台系统下测试过,基本上没问题,如果你碰到什么问题,可以在评论里给我留言,欢迎斧正!

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/153982.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号