首页

关于常用文件操作工具类FileUtil可以修改文件的最后访问时间、目录文件判断及列表list等处理

标签:文件操作工具类,FileUtil,修改文件的最后访问时间,目录文件判断,列表list     发布时间:2018-07-31   

一、前言

对于常用FileUtil文件操作工具类,对文件最后访问时间进行touch修改、 判断指定的文件isFileExist是否存在、创建指定的目录makeDirectory、得到getFileType文件的类型。

二、代码示例

package com.xwood.util;@b@@b@import java.io.BufferedReader;@b@import java.io.File;@b@import java.io.FileInputStream;@b@import java.io.FileOutputStream;@b@import java.io.FileReader;@b@import java.io.FileWriter;@b@import java.io.IOException;@b@import java.net.MalformedURLException;@b@import java.net.URL;@b@import java.util.ArrayList;@b@@b@/**@b@ * 此类中封装一些常用的文件操作。@b@ * 所有方法都是静态方法,不需要生成此类的实例,@b@ * 为避免生成此类的实例,构造方法被申明为private类型的。@b@ * @since  1.0@b@ */@b@@b@public class FileUtil {@b@  /**@b@   * 私有构造方法,防止类的实例化,因为工具类不需要实例化。@b@   */@b@  private FileUtil() {@b@@b@  }@b@@b@  /**@b@   * 修改文件的最后访问时间。@b@   * 如果文件不存在则创建该文件。@b@   * <b>目前这个方法的行为方式还不稳定,主要是方法有些信息输出,这些信息输出是否保留还在考虑中。</b>@b@   * @param file 需要修改最后访问时间的文件。@b@   * @since  1.0@b@   */@b@  public static void touch(File file) {@b@    long currentTime = System.currentTimeMillis();@b@    if (!file.exists()) {@b@      System.err.println("file not found:" + file.getName());@b@      System.err.println("Create a new file:" + file.getName());@b@      try {@b@        if (file.createNewFile()) {@b@          System.out.println("Succeeded!");@b@        }@b@        else {@b@          System.err.println("Create file failed!");@b@        }@b@      }@b@      catch (IOException e) {@b@        System.err.println("Create file failed!");@b@        e.printStackTrace();@b@      }@b@    }@b@    boolean result = file.setLastModified(currentTime);@b@    if (!result) {@b@      System.err.println("touch failed: " + file.getName());@b@    }@b@  }@b@@b@  /**@b@   * 修改文件的最后访问时间。@b@   * 如果文件不存在则创建该文件。@b@   * <b>目前这个方法的行为方式还不稳定,主要是方法有些信息输出,这些信息输出是否保留还在考虑中。</b>@b@   * @param fileName 需要修改最后访问时间的文件的文件名。@b@   * @since  1.0@b@   */@b@  public static void touch(String fileName) {@b@    File file = new File(fileName);@b@    touch(file);@b@  }@b@@b@  /**@b@   * 修改文件的最后访问时间。@b@   * 如果文件不存在则创建该文件。@b@   * <b>目前这个方法的行为方式还不稳定,主要是方法有些信息输出,这些信息输出是否保留还在考虑中。</b>@b@   * @param files 需要修改最后访问时间的文件数组。@b@   * @since  1.0@b@   */@b@  public static void touch(File[] files) {@b@    for (int i = 0; i < files.length; i++) {@b@      touch(files[i]);@b@    }@b@  }@b@@b@  /**@b@   * 修改文件的最后访问时间。@b@   * 如果文件不存在则创建该文件。@b@   * <b>目前这个方法的行为方式还不稳定,主要是方法有些信息输出,这些信息输出是否保留还在考虑中。</b>@b@   * @param fileNames 需要修改最后访问时间的文件名数组。@b@   * @since  1.0@b@   */@b@  public static void touch(String[] fileNames) {@b@    File[] files = new File[fileNames.length];@b@    for (int i = 0; i < fileNames.length; i++) {@b@      files[i] = new File(fileNames[i]);@b@    }@b@    touch(files);@b@  }@b@@b@  /**@b@   * 判断指定的文件是否存在。@b@   * @param fileName 要判断的文件的文件名@b@   * @return 存在时返回true,否则返回false。@b@   * @since  1.0@b@   */@b@  public static boolean isFileExist(String fileName) {@b@    return new File(fileName).isFile();@b@  }@b@@b@  /**@b@   * 创建指定的目录。@b@   * 如果指定的目录的父目录不存在则创建其目录书上所有需要的父目录。@b@   * <b>注意:可能会在返回false的时候创建部分父目录。</b>@b@   * @param file 要创建的目录@b@   * @return 完全创建成功时返回true,否则返回false。@b@   * @since  1.0@b@   */@b@  public static boolean makeDirectory(File file) {@b@    File parent = file.getParentFile();@b@    if (parent != null) {@b@      return parent.mkdirs();@b@    }@b@    return false;@b@  }@b@@b@  /**	@b@   * 创建指定的目录。@b@   * 如果指定的目录的父目录不存在则创建其目录书上所有需要的父目录。@b@   * <b>注意:可能会在返回false的时候创建部分父目录。</b>@b@   * @param fileName 要创建的目录的目录名@b@   * @return 完全创建成功时返回true,否则返回false。@b@   * @since  1.0@b@   */@b@  public static boolean makeDirectory(String fileName) {@b@    File file = new File(fileName);@b@    return makeDirectory(file);@b@  }@b@@b@  /**@b@   * 清空指定目录中的文件。@b@   * 这个方法将尽可能删除所有的文件,但是只要有一个文件没有被删除都会返回false。@b@   * 另外这个方法不会迭代删除,即不会删除子目录及其内容。@b@   * @param directory 要清空的目录@b@   * @return 目录下的所有文件都被成功删除时返回true,否则返回false.@b@   * @since  1.0@b@   */@b@  public static boolean emptyDirectory(File directory) {@b@    boolean result = true;@b@    File[] entries = directory.listFiles();@b@    for (int i = 0; i < entries.length; i++) {@b@      if (!entries[i].delete()) {@b@        result = false;@b@      }@b@    }@b@    return result;@b@  }@b@@b@  /**@b@   * 清空指定目录中的文件。@b@   * 这个方法将尽可能删除所有的文件,但是只要有一个文件没有被删除都会返回false。@b@   * 另外这个方法不会迭代删除,即不会删除子目录及其内容。@b@   * @param directoryName 要清空的目录的目录名@b@   * @return 目录下的所有文件都被成功删除时返回true,否则返回false。@b@   * @since  1.0@b@   */@b@  public static boolean emptyDirectory(String directoryName) {@b@    File dir = new File(directoryName);@b@    return emptyDirectory(dir);@b@  }@b@@b@  /**@b@   * 删除指定目录及其中的所有内容。@b@   * @param dirName 要删除的目录的目录名@b@   * @return 删除成功时返回true,否则返回false。@b@   * @since  1.0@b@   */@b@  public static boolean deleteDirectory(String dirName) {@b@    return deleteDirectory(new File(dirName));@b@  }@b@@b@  /**@b@   * 删除指定目录及其中的所有内容。@b@   * @param dir 要删除的目录@b@   * @return 删除成功时返回true,否则返回false。@b@   * @since  1.0@b@   */@b@  public static boolean deleteDirectory(File dir) {@b@    if ( (dir == null) || !dir.isDirectory()) {@b@      throw new IllegalArgumentException("Argument " + dir +@b@                                         " is not a directory. ");@b@    }@b@@b@    File[] entries = dir.listFiles();@b@    int sz = entries.length;@b@@b@    for (int i = 0; i < sz; i++) {@b@      if (entries[i].isDirectory()) {@b@        if (!deleteDirectory(entries[i])) {@b@          return false;@b@        }@b@      }@b@      else {@b@        if (!entries[i].delete()) {@b@          return false;@b@        }@b@      }@b@    }@b@@b@    if (!dir.delete()) {@b@      return false;@b@    }@b@    return true;@b@  }@b@@b@  /**@b@   * 列出目录中的所有内容,包括其子目录中的内容。@b@   * @param fileName 要列出的目录的目录名@b@   * @return 目录内容的文件数组。@b@   * @since  1.0@b@   */@b@  /*public static File[] listAll(String fileName) {@b@    return listAll(new File(fileName));@b@  }*/@b@@b@  /**@b@   * 列出目录中的所有内容,包括其子目录中的内容。@b@   * @param file 要列出的目录@b@   * @return 目录内容的文件数组。@b@   * @since  1.0@b@   */@b@  /*public static File[] listAll(File file) {@b@    ArrayList list = new ArrayList();@b@    File[] files;@b@    if (!file.exists() || file.isFile()) {@b@      return null;@b@    }@b@    list(list, file, new AllFileFilter());@b@    list.remove(file);@b@    files = new File[list.size()];@b@    list.toArray(files);@b@    return files;@b@  }*/@b@@b@  /**@b@   * 列出目录中的所有内容,包括其子目录中的内容。@b@   * @param file 要列出的目录@b@   * @param filter 过滤器@b@   * @return 目录内容的文件数组。@b@   * @since  1.0@b@   */@b@  public static File[] listAll(File file,@b@                               javax.swing.filechooser.FileFilter filter) {@b@    ArrayList list = new ArrayList();@b@    File[] files;@b@    if (!file.exists() || file.isFile()) {@b@      return null;@b@    }@b@    list(list, file, filter);@b@    files = new File[list.size()];@b@    list.toArray(files);@b@    return files;@b@  }@b@@b@  /**@b@   * 将目录中的内容添加到列表。@b@   * @param list 文件列表@b@   * @param filter 过滤器@b@   * @param file 目录@b@   */@b@  private static void list(ArrayList list, File file,@b@                           javax.swing.filechooser.FileFilter filter) {@b@    if (filter.accept(file)) {@b@      list.add(file);@b@      if (file.isFile()) {@b@        return;@b@      }@b@    }@b@    if (file.isDirectory()) {@b@      File files[] = file.listFiles();@b@      for (int i = 0; i < files.length; i++) {@b@        list(list, files[i], filter);@b@      }@b@    }@b@@b@  }@b@@b@  /**@b@   * 返回文件的URL地址。@b@   * @param file 文件@b@   * @return 文件对应的的URL地址@b@   * @throws MalformedURLException@b@   * @since  1.0@b@   * @deprecated 在实现的时候没有注意到File类本身带一个toURL方法将文件路径转换为URL。@b@   *             请使用File.toURL方法。@b@   */@b@  public static URL getURL(File file) throws MalformedURLException {@b@    String fileURL = "file:/" + file.getAbsolutePath();@b@    URL url = new URL(fileURL);@b@    return url;@b@  }@b@@b@  /**@b@   * 从文件路径得到文件名。@b@   * @param filePath 文件的路径,可以是相对路径也可以是绝对路径@b@   * @return 对应的文件名@b@   * @since  1.0@b@   */@b@  public static String getFileName(String filePath) {@b@    File file = new File(filePath);@b@    return file.getName();@b@  }@b@@b@  /**@b@   * 从文件名得到文件绝对路径。@b@   * @param fileName 文件名@b@   * @return 对应的文件路径@b@   * @since  1.0@b@   */@b@  public static String getFilePath(String fileName) {@b@    File file = new File(fileName);@b@    return file.getAbsolutePath();@b@  }@b@@b@  /**@b@   * 将DOS/Windows格式的路径转换为UNIX/Linux格式的路径。@b@   * 其实就是将路径中的"\"全部换为"/",因为在某些情况下我们转换为这种方式比较方便,@b@   * 某中程度上说"/"比"\"更适合作为路径分隔符,而且DOS/Windows也将它当作路径分隔符。@b@   * @param filePath 转换前的路径@b@   * @return 转换后的路径@b@   * @since  1.0@b@   */@b@  public static String toUNIXpath(String filePath) {@b@    return filePath.replace('\\', '/');@b@  }@b@@b@  /**@b@   * 从文件名得到UNIX风格的文件绝对路径。@b@   * @param fileName 文件名@b@   * @return 对应的UNIX风格的文件路径@b@   * @since  1.0@b@   * @see #toUNIXpath(String filePath) toUNIXpath@b@   */@b@  public static String getUNIXfilePath(String fileName) {@b@    File file = new File(fileName);@b@    return toUNIXpath(file.getAbsolutePath());@b@  }@b@@b@  /**@b@   * 得到文件的类型。@b@   * 实际上就是得到文件名中最后一个“.”后面的部分。@b@   * @param fileName 文件名@b@   * @return 文件名中的类型部分@b@   * @since  1.0@b@   */@b@  public static String getTypePart(String fileName) {@b@    int point = fileName.lastIndexOf('.');@b@    int length = fileName.length();@b@    if (point == -1 || point == length - 1) {@b@      return "";@b@    }@b@    else {@b@      return fileName.substring(point + 1, length);@b@    }@b@  }@b@@b@  /**@b@   * 得到文件的类型。@b@   * 实际上就是得到文件名中最后一个“.”后面的部分。@b@   * @param file 文件@b@   * @return 文件名中的类型部分@b@   * @since  1.0@b@   */@b@  public static String getFileType(File file) {@b@    return getTypePart(file.getName());@b@  }@b@@b@  /**@b@   * 得到文件的名字部分。@b@   * 实际上就是路径中的最后一个路径分隔符后的部分。@b@   * @param fileName 文件名@b@   * @return 文件名中的名字部分@b@   * @since  1.0@b@   */@b@  public static String getNamePart(String fileName) {@b@    int point = getPathLsatIndex(fileName);@b@    int length = fileName.length();@b@    if (point == -1) {@b@      return fileName;@b@    }@b@    else if (point == length - 1) {@b@      int secondPoint = getPathLsatIndex(fileName, point - 1);@b@      if (secondPoint == -1) {@b@        if (length == 1) {@b@          return fileName;@b@        }@b@        else {@b@          return fileName.substring(0, point);@b@        }@b@      }@b@      else {@b@        return fileName.substring(secondPoint + 1, point);@b@      }@b@    }@b@    else {@b@      return fileName.substring(point + 1);@b@    }@b@  }@b@@b@  /**@b@   * 得到文件名中的父路径部分。@b@   * 对两种路径分隔符都有效。@b@   * 不存在时返回""。@b@   * 如果文件名是以路径分隔符结尾的则不考虑该分隔符,例如"/path/"返回""。@b@   * @param fileName 文件名@b@   * @return 父路径,不存在或者已经是父目录时返回""@b@   * @since  1.0@b@   */@b@  public static String getPathPart(String fileName) {@b@    int point = getPathLsatIndex(fileName);@b@    int length = fileName.length();@b@    if (point == -1) {@b@      return "";@b@    }@b@    else if (point == length - 1) {@b@      int secondPoint = getPathLsatIndex(fileName, point - 1);@b@      if (secondPoint == -1) {@b@        return "";@b@      }@b@      else {@b@        return fileName.substring(0, secondPoint);@b@      }@b@    }@b@    else {@b@      return fileName.substring(0, point);@b@    }@b@  }@b@@b@  /**@b@   * 得到路径分隔符在文件路径中首次出现的位置。@b@   * 对于DOS或者UNIX风格的分隔符都可以。@b@   * @param fileName 文件路径@b@   * @return 路径分隔符在路径中首次出现的位置,没有出现时返回-1。@b@   * @since  1.0@b@   */@b@  public static int getPathIndex(String fileName) {@b@    int point = fileName.indexOf('/');@b@    if (point == -1) {@b@      point = fileName.indexOf('\\');@b@    }@b@    return point;@b@  }@b@@b@  /**@b@   * 得到路径分隔符在文件路径中指定位置后首次出现的位置。@b@   * 对于DOS或者UNIX风格的分隔符都可以。@b@   * @param fileName 文件路径@b@   * @param fromIndex 开始查找的位置@b@   * @return 路径分隔符在路径中指定位置后首次出现的位置,没有出现时返回-1。@b@   * @since  1.0@b@   */@b@  public static int getPathIndex(String fileName, int fromIndex) {@b@    int point = fileName.indexOf('/', fromIndex);@b@    if (point == -1) {@b@      point = fileName.indexOf('\\', fromIndex);@b@    }@b@    return point;@b@  }@b@@b@  /**@b@   * 得到路径分隔符在文件路径中最后出现的位置。@b@   * 对于DOS或者UNIX风格的分隔符都可以。@b@   * @param fileName 文件路径@b@   * @return 路径分隔符在路径中最后出现的位置,没有出现时返回-1。@b@   * @since  1.0@b@   */@b@  public static int getPathLsatIndex(String fileName) {@b@    int point = fileName.lastIndexOf('/');@b@    if (point == -1) {@b@      point = fileName.lastIndexOf('\\');@b@    }@b@    return point;@b@  }@b@@b@  /**@b@   * 得到路径分隔符在文件路径中指定位置前最后出现的位置。@b@   * 对于DOS或者UNIX风格的分隔符都可以。@b@   * @param fileName 文件路径@b@   * @param fromIndex 开始查找的位置@b@   * @return 路径分隔符在路径中指定位置前最后出现的位置,没有出现时返回-1。@b@   * @since  1.0@b@   */@b@  public static int getPathLsatIndex(String fileName, int fromIndex) {@b@    int point = fileName.lastIndexOf('/', fromIndex);@b@    if (point == -1) {@b@      point = fileName.lastIndexOf('\\', fromIndex);@b@    }@b@    return point;@b@  }@b@@b@  /**@b@   * 将文件名中的类型部分去掉。@b@   * @param filename 文件名@b@   * @return 去掉类型部分的结果@b@   * @since  1.0@b@   */@b@  public static String trimType(String filename) {@b@    int index = filename.lastIndexOf(".");@b@    if (index != -1) {@b@      return filename.substring(0, index);@b@    }@b@    else {@b@      return filename;@b@    }@b@  }@b@  /**@b@   * 得到相对路径。@b@   * 文件名不是目录名的子节点时返回文件名。@b@   * @param pathName 目录名@b@   * @param fileName 文件名@b@   * @return 得到文件名相对于目录名的相对路径,目录下不存在该文件时返回文件名@b@   * @since  1.0@b@   */@b@  public static String getSubpath(String pathName,String fileName) {@b@    int index = fileName.indexOf(pathName);@b@    if (index != -1) {@b@      return fileName.substring(index + pathName.length() + 1);@b@    }@b@    else {@b@      return fileName;@b@    }@b@  }@b@@b@  /**@b@   * 检查给定目录的存在性@b@   * 保证指定的路径可用,如果指定的路径不存在,那么建立该路径,可以为多级路径@b@   * @param path@b@   * @return 真假值@b@   * @since  1.0@b@   */@b@   public static final boolean pathValidate(String path)@b@   {@b@     //String path="d:/web/www/sub";@b@     //System.out.println(path);@b@     //path = getUNIXfilePath(path);@b@@b@     //path = ereg_replace("^\\/+", "", path);@b@     //path = ereg_replace("\\/+$", "", path);@b@     String[] arraypath = path.split("/");@b@     String tmppath = "";@b@     for (int i = 0; i < arraypath.length; i++)@b@     {@b@       tmppath += "/" + arraypath[i];@b@       File d = new File(tmppath.substring(1));@b@       if (!d.exists()) { //检查Sub目录是否存在@b@           System.out.println(tmppath.substring(1));@b@         if (!d.mkdir())@b@         {@b@           return false;@b@         }@b@       }@b@     }@b@     return true;@b@   }@b@@b@   /**@b@    * 读取文件的内容@b@    * 读取指定文件的内容@b@    * @param path 为要读取文件的绝对路径@b@    * @return 以行读取文件后的内容。@b@    * @since  1.0@b@    */@b@   public static final String getFileContent(String path) throws IOException@b@   {@b@     String filecontent = "";@b@     try {@b@       File f = new File(path);@b@       if (f.exists()) {@b@         FileReader fr = new FileReader(path);@b@         BufferedReader br = new BufferedReader(fr); //建立BufferedReader对象,并实例化为br@b@         String line = br.readLine(); //从文件读取一行字符串@b@         //判断读取到的字符串是否不为空@b@         while (line != null) {@b@           filecontent += line + "\n";@b@           line = br.readLine(); //从文件中继续读取一行数据@b@         }@b@         br.close(); //关闭BufferedReader对象@b@         fr.close(); //关闭文件@b@       }@b@@b@     }@b@     catch (IOException e) {@b@       throw e;@b@     }@b@     return filecontent;@b@   }@b@@b@   /**@b@    * 根据内容生成文件@b@    * @param path要生成文件的绝对路径,@b@    * @param 文件的内容。@b@    * @return 真假值@b@    * @since  1.0@b@    */@b@   public static final boolean genModuleTpl(String path, String modulecontent)  throws IOException@b@   {@b@@b@     path = getUNIXfilePath(path);@b@     String[] patharray = path.split("\\/");@b@     String modulepath = "";@b@     for (int i = 0; i < patharray.length - 1; i++) {@b@       modulepath += "/" + patharray[i];@b@     }@b@     File d = new File(modulepath.substring(1));@b@     if (!d.exists()) {@b@       if (!pathValidate(modulepath.substring(1))) {@b@         return false;@b@       }@b@     }@b@     try {@b@       FileWriter fw = new FileWriter(path); //建立FileWriter对象,并实例化fw@b@       //将字符串写入文件@b@       fw.write(modulecontent);@b@       fw.close();@b@     }@b@     catch (IOException e) {@b@       throw e;@b@     }@b@     return true;@b@   }@b@@b@   /**@b@    * 获取图片文件的扩展名(发布系统专用)@b@    * @param picname 为图片名称加上前面的路径不包括扩展名@b@    * @return 图片的扩展名@b@    * @since  1.0@b@    */@b@   public static final String getPicExtendName(String pic_path)@b@   {@b@     pic_path = getUNIXfilePath(pic_path);@b@     String pic_extend = "";@b@     if (isFileExist(pic_path + ".gif"))@b@     {@b@       pic_extend = ".gif";@b@     }@b@     if (isFileExist(pic_path + ".jpeg"))@b@     {@b@       pic_extend = ".jpeg";@b@     }@b@     if (isFileExist(pic_path + ".jpg"))@b@     {@b@       pic_extend = ".jpg";@b@     }@b@     if (isFileExist(pic_path + ".png"))@b@     {@b@       pic_extend = ".png";@b@     }@b@     return pic_extend; //返回图片扩展名@b@   }@b@   //拷贝文件@b@   public static final boolean CopyFile(File in, File out) throws Exception {@b@       try {@b@           FileInputStream fis = new FileInputStream(in);@b@           FileOutputStream fos = new FileOutputStream(out);@b@           byte[] buf = new byte[1024];@b@           int i = 0;@b@           while ((i = fis.read(buf)) != -1) {@b@               fos.write(buf, 0, i);@b@           }@b@           fis.close();@b@           fos.close();@b@           return true;@b@       } catch (IOException ie) {@b@           ie.printStackTrace();@b@           return false;@b@       }@b@   }@b@   //拷贝文件@b@   public static final boolean CopyFile(String infile, String outfile) throws Exception {@b@       try {@b@           File in = new File(infile);@b@           File out = new File(outfile);@b@           return CopyFile(in, out);@b@       } catch (IOException ie) {@b@           ie.printStackTrace();@b@           return false;@b@       }@b@@b@   }@b@   /**@b@    * 计算图片数量@b@    * @param id@b@    * @param dtime@b@    * @return@b@    */@b@   public static final int countPics(String id,String dtime,String extensions){@b@	   int counts = 0; @b@	   @b@	   MyFileFilter mfilter = new MyFileFilter(extensions.split(","));@b@       PropsUtil pu = new PropsUtil();@b@       String PICROOT = pu.readSingleProps("DestinationsPICROOT").trim();@b@       String path = PICROOT + "/"+dtime.substring(0, 10) + "/";@b@       File lfile = new File(path);@b@       String filename;@b@       if(lfile.isDirectory()){@b@    	   File[] files = lfile.listFiles(mfilter);@b@    	   for(int i=0;i<files.length;i++){@b@    		   filename = files[i].getName();@b@    		   if((filename.indexOf(id + "_")==0)&&(filename.indexOf("_small")>-1))@b@    			   counts ++;@b@    	   }@b@    	   files = null;@b@       }@b@       filename = null;@b@       lfile = null;@b@       pu = null;@b@       mfilter = null;@b@    	   @b@	   return counts;@b@   }@b@@b@}