首页

基于apache的FileUtils工具类实现对文件file打开文件方式、URL转换及复制方式、读入方式及写入移动等常用操作

标签:文件工具类,FileUtils,apache,apache-rat,toURLs,目录文件复制、移动、删除,IOUtils     发布时间:2017-12-28   

一、前言

通过apache-rat(0.9)包中的org.apache.commons.io.FileUtils文件工具类,对文件目录常用的操作(对其打开openInputStream、复制copyFile、列举listFiles、移动及删除方式deleteDirectory)、文件url转换toURLs\toFiles及统一友好的关闭操作(closeQuietly),具体如下代码所示。

二、源码说明

1.FileUtils工具类

package org.apache.commons.io;@b@@b@import java.io.File;@b@import java.io.FileFilter;@b@import java.io.FileInputStream;@b@import java.io.FileNotFoundException;@b@import java.io.FileOutputStream;@b@import java.io.IOException;@b@import java.io.InputStream;@b@import java.io.OutputStream;@b@import java.net.URL;@b@import java.util.ArrayList;@b@import java.util.Collection;@b@import java.util.Date;@b@import java.util.Iterator;@b@import java.util.LinkedList;@b@import java.util.List;@b@import java.util.zip.CRC32;@b@import java.util.zip.CheckedInputStream;@b@import java.util.zip.Checksum;@b@import org.apache.commons.io.filefilter.DirectoryFileFilter;@b@import org.apache.commons.io.filefilter.FalseFileFilter;@b@import org.apache.commons.io.filefilter.FileFilterUtils;@b@import org.apache.commons.io.filefilter.IOFileFilter;@b@import org.apache.commons.io.filefilter.SuffixFileFilter;@b@import org.apache.commons.io.filefilter.TrueFileFilter;@b@import org.apache.commons.io.output.NullOutputStream;@b@@b@public class FileUtils@b@{@b@  public static final long ONE_KB = 1024L;@b@  public static final long ONE_MB = 1048576L;@b@  public static final long ONE_GB = 1073741824L;@b@  public static final File[] EMPTY_FILE_ARRAY = new File[0];@b@@b@  public static FileInputStream openInputStream(File file)@b@    throws IOException@b@  {@b@    if (file.exists()) {@b@      if (file.isDirectory())@b@        throw new IOException("File '" + file + "' exists but is a directory");@b@@b@      if (file.canRead()) break label117;@b@      throw new IOException("File '" + file + "' cannot be read");@b@    }@b@@b@    throw new FileNotFoundException("File '" + file + "' does not exist");@b@@b@    label117: return new FileInputStream(file);@b@  }@b@@b@  public static FileOutputStream openOutputStream(File file)@b@    throws IOException@b@  {@b@    if (file.exists()) {@b@      if (file.isDirectory())@b@        throw new IOException("File '" + file + "' exists but is a directory");@b@@b@      if (file.canWrite()) break label140;@b@      throw new IOException("File '" + file + "' cannot be written to");@b@    }@b@@b@    File parent = file.getParentFile();@b@    if ((parent != null) && (!(parent.exists())) && @b@      (!(parent.mkdirs()))) {@b@      throw new IOException("File '" + file + "' could not be created");@b@    }@b@@b@    label140: return new FileOutputStream(file);@b@  }@b@@b@  public static String byteCountToDisplaySize(long size)@b@  {@b@    String displaySize;@b@    if (size / 1073741824L > 0L)@b@      displaySize = String.valueOf(size / 1073741824L) + " GB";@b@    else if (size / 1048576L > 0L)@b@      displaySize = String.valueOf(size / 1048576L) + " MB";@b@    else if (size / 1024L > 0L)@b@      displaySize = String.valueOf(size / 1024L) + " KB";@b@    else@b@      displaySize = String.valueOf(size) + " bytes";@b@@b@    return displaySize;@b@  }@b@@b@  public static void touch(File file)@b@    throws IOException@b@  {@b@    if (!(file.exists())) {@b@      OutputStream out = openOutputStream(file);@b@      IOUtils.closeQuietly(out);@b@    }@b@    boolean success = file.setLastModified(System.currentTimeMillis());@b@    if (!(success))@b@      throw new IOException("Unable to set the last modification time for " + file);@b@  }@b@@b@  public static File[] convertFileCollectionToFileArray(Collection files)@b@  {@b@    return ((File[])(File[])files.toArray(new File[files.size()]));@b@  }@b@@b@  private static void innerListFiles(Collection files, File directory, IOFileFilter filter)@b@  {@b@    int i;@b@    File[] found = directory.listFiles(filter);@b@    if (found != null)@b@      for (i = 0; i < found.length; ++i)@b@        if (found[i].isDirectory())@b@          innerListFiles(files, found[i], filter);@b@        else@b@          files.add(found[i]);@b@  }@b@@b@  public static Collection listFiles(File directory, IOFileFilter fileFilter, IOFileFilter dirFilter)@b@  {@b@    IOFileFilter effDirFilter;@b@    if (!(directory.isDirectory())) {@b@      throw new IllegalArgumentException("Parameter 'directory' is not a directory");@b@    }@b@@b@    if (fileFilter == null) {@b@      throw new NullPointerException("Parameter 'fileFilter' is null");@b@    }@b@@b@    IOFileFilter effFileFilter = FileFilterUtils.andFileFilter(fileFilter, FileFilterUtils.notFileFilter(DirectoryFileFilter.INSTANCE));@b@@b@    if (dirFilter == null)@b@      effDirFilter = FalseFileFilter.INSTANCE;@b@    else {@b@      effDirFilter = FileFilterUtils.andFileFilter(dirFilter, DirectoryFileFilter.INSTANCE);@b@    }@b@@b@    Collection files = new LinkedList();@b@    innerListFiles(files, directory, FileFilterUtils.orFileFilter(effFileFilter, effDirFilter));@b@@b@    return files;@b@  }@b@@b@  public static Iterator iterateFiles(File directory, IOFileFilter fileFilter, IOFileFilter dirFilter)@b@  {@b@    return listFiles(directory, fileFilter, dirFilter).iterator();@b@  }@b@@b@  private static String[] toSuffixes(String[] extensions)@b@  {@b@    String[] suffixes = new String[extensions.length];@b@    for (int i = 0; i < extensions.length; ++i)@b@      suffixes[i] = "." + extensions[i];@b@@b@    return suffixes;@b@  }@b@@b@  public static Collection listFiles(File directory, String[] extensions, boolean recursive)@b@  {@b@    IOFileFilter filter;@b@    if (extensions == null) {@b@      filter = TrueFileFilter.INSTANCE;@b@    } else {@b@      String[] suffixes = toSuffixes(extensions);@b@      filter = new SuffixFileFilter(suffixes);@b@    }@b@    return listFiles(directory, filter, (recursive) ? TrueFileFilter.INSTANCE : FalseFileFilter.INSTANCE);@b@  }@b@@b@  public static Iterator iterateFiles(File directory, String[] extensions, boolean recursive)@b@  {@b@    return listFiles(directory, extensions, recursive).iterator();@b@  }@b@@b@  public static boolean contentEquals(File file1, File file2)@b@    throws IOException@b@  {@b@    boolean file1Exists = file1.exists();@b@    if (file1Exists != file2.exists()) {@b@      return false;@b@    }@b@@b@    if (!(file1Exists))@b@    {@b@      return true;@b@    }@b@@b@    if ((file1.isDirectory()) || (file2.isDirectory()))@b@    {@b@      throw new IOException("Can't compare directories, only files");@b@    }@b@@b@    if (file1.length() != file2.length())@b@    {@b@      return false;@b@    }@b@@b@    if (file1.getCanonicalFile().equals(file2.getCanonicalFile()))@b@    {@b@      return true;@b@    }@b@@b@    InputStream input1 = null;@b@    InputStream input2 = null;@b@    try {@b@      input1 = new FileInputStream(file1);@b@      input2 = new FileInputStream(file2);@b@      boolean bool1 = IOUtils.contentEquals(input1, input2);@b@@b@      return bool1;@b@    }@b@    finally@b@    {@b@      IOUtils.closeQuietly(input1);@b@      IOUtils.closeQuietly(input2);@b@    }@b@  }@b@@b@  public static File toFile(URL url)@b@  {@b@    if ((url == null) || (!(url.getProtocol().equals("file"))))@b@      return null;@b@@b@    String filename = url.getFile().replace('/', File.separatorChar);@b@    int pos = 0;@b@    while (true) { do if ((pos = filename.indexOf(37, pos)) < 0) break label113;@b@      while (pos + 2 >= filename.length());@b@      String hexStr = filename.substring(pos + 1, pos + 3);@b@      char ch = (char)Integer.parseInt(hexStr, 16);@b@      filename = filename.substring(0, pos) + ch + filename.substring(pos + 3);@b@    }@b@@b@    label113: return new File(filename);@b@  }@b@@b@  public static File[] toFiles(URL[] urls)@b@  {@b@    if ((urls == null) || (urls.length == 0))@b@      return EMPTY_FILE_ARRAY;@b@@b@    File[] files = new File[urls.length];@b@    for (int i = 0; i < urls.length; ++i) {@b@      URL url = urls[i];@b@      if (url != null) {@b@        if (!(url.getProtocol().equals("file"))) {@b@          throw new IllegalArgumentException("URL could not be converted to a File: " + url);@b@        }@b@@b@        files[i] = toFile(url);@b@      }@b@    }@b@    return files;@b@  }@b@@b@  public static URL[] toURLs(File[] files)@b@    throws IOException@b@  {@b@    URL[] urls = new URL[files.length];@b@@b@    for (int i = 0; i < urls.length; ++i) {@b@      urls[i] = files[i].toURL();@b@    }@b@@b@    return urls;@b@  }@b@@b@  public static void copyFileToDirectory(File srcFile, File destDir)@b@    throws IOException@b@  {@b@    copyFileToDirectory(srcFile, destDir, true);@b@  }@b@@b@  public static void copyFileToDirectory(File srcFile, File destDir, boolean preserveFileDate)@b@    throws IOException@b@  {@b@    if (destDir == null)@b@      throw new NullPointerException("Destination must not be null");@b@@b@    if ((destDir.exists()) && (!(destDir.isDirectory())))@b@      throw new IllegalArgumentException("Destination '" + destDir + "' is not a directory");@b@@b@    copyFile(srcFile, new File(destDir, srcFile.getName()), preserveFileDate);@b@  }@b@@b@  public static void copyFile(File srcFile, File destFile)@b@    throws IOException@b@  {@b@    copyFile(srcFile, destFile, true);@b@  }@b@@b@  public static void copyFile(File srcFile, File destFile, boolean preserveFileDate)@b@    throws IOException@b@  {@b@    if (srcFile == null)@b@      throw new NullPointerException("Source must not be null");@b@@b@    if (destFile == null)@b@      throw new NullPointerException("Destination must not be null");@b@@b@    if (!(srcFile.exists()))@b@      throw new FileNotFoundException("Source '" + srcFile + "' does not exist");@b@@b@    if (srcFile.isDirectory())@b@      throw new IOException("Source '" + srcFile + "' exists but is a directory");@b@@b@    if (srcFile.getCanonicalPath().equals(destFile.getCanonicalPath()))@b@      throw new IOException("Source '" + srcFile + "' and destination '" + destFile + "' are the same");@b@@b@    if ((destFile.getParentFile() != null) && (!(destFile.getParentFile().exists())) && @b@      (!(destFile.getParentFile().mkdirs()))) {@b@      throw new IOException("Destination '" + destFile + "' directory cannot be created");@b@    }@b@@b@    if ((destFile.exists()) && (!(destFile.canWrite())))@b@      throw new IOException("Destination '" + destFile + "' exists but is read-only");@b@@b@    doCopyFile(srcFile, destFile, preserveFileDate);@b@  }@b@@b@  private static void doCopyFile(File srcFile, File destFile, boolean preserveFileDate)@b@    throws IOException@b@  {@b@    if ((destFile.exists()) && (destFile.isDirectory())) {@b@      throw new IOException("Destination '" + destFile + "' exists but is a directory");@b@    }@b@@b@    FileInputStream input = new FileInputStream(srcFile);@b@    try {@b@      FileOutputStream output = new FileOutputStream(destFile);@b@      try {@b@        IOUtils.copy(input, output);@b@      } finally {@b@        IOUtils.closeQuietly(output);@b@      }@b@    } finally {@b@      IOUtils.closeQuietly(input);@b@    }@b@@b@    if (srcFile.length() != destFile.length()) {@b@      throw new IOException("Failed to copy full contents from '" + srcFile + "' to '" + destFile + "'");@b@    }@b@@b@    if (preserveFileDate)@b@      destFile.setLastModified(srcFile.lastModified());@b@  }@b@@b@  public static void copyDirectoryToDirectory(File srcDir, File destDir)@b@    throws IOException@b@  {@b@    if (srcDir == null)@b@      throw new NullPointerException("Source must not be null");@b@@b@    if ((srcDir.exists()) && (!(srcDir.isDirectory())))@b@      throw new IllegalArgumentException("Source '" + destDir + "' is not a directory");@b@@b@    if (destDir == null)@b@      throw new NullPointerException("Destination must not be null");@b@@b@    if ((destDir.exists()) && (!(destDir.isDirectory())))@b@      throw new IllegalArgumentException("Destination '" + destDir + "' is not a directory");@b@@b@    copyDirectory(srcDir, new File(destDir, srcDir.getName()), true);@b@  }@b@@b@  public static void copyDirectory(File srcDir, File destDir)@b@    throws IOException@b@  {@b@    copyDirectory(srcDir, destDir, true);@b@  }@b@@b@  public static void copyDirectory(File srcDir, File destDir, boolean preserveFileDate)@b@    throws IOException@b@  {@b@    copyDirectory(srcDir, destDir, null, preserveFileDate);@b@  }@b@@b@  public static void copyDirectory(File srcDir, File destDir, FileFilter filter)@b@    throws IOException@b@  {@b@    copyDirectory(srcDir, destDir, filter, true);@b@  }@b@@b@  public static void copyDirectory(File srcDir, File destDir, FileFilter filter, boolean preserveFileDate)@b@    throws IOException@b@  {@b@    File[] srcFiles;@b@    int i;@b@    if (srcDir == null)@b@      throw new NullPointerException("Source must not be null");@b@@b@    if (destDir == null)@b@      throw new NullPointerException("Destination must not be null");@b@@b@    if (!(srcDir.exists()))@b@      throw new FileNotFoundException("Source '" + srcDir + "' does not exist");@b@@b@    if (!(srcDir.isDirectory()))@b@      throw new IOException("Source '" + srcDir + "' exists but is not a directory");@b@@b@    if (srcDir.getCanonicalPath().equals(destDir.getCanonicalPath())) {@b@      throw new IOException("Source '" + srcDir + "' and destination '" + destDir + "' are the same");@b@    }@b@@b@    List exclusionList = null;@b@    if (destDir.getCanonicalPath().startsWith(srcDir.getCanonicalPath())) {@b@      srcFiles = (filter == null) ? srcDir.listFiles() : srcDir.listFiles(filter);@b@      if ((srcFiles != null) && (srcFiles.length > 0)) {@b@        exclusionList = new ArrayList(srcFiles.length);@b@        for (i = 0; i < srcFiles.length; ++i) {@b@          File copiedFile = new File(destDir, srcFiles[i].getName());@b@          exclusionList.add(copiedFile.getCanonicalPath());@b@        }@b@      }@b@    }@b@    doCopyDirectory(srcDir, destDir, filter, preserveFileDate, exclusionList);@b@  }@b@@b@  private static void doCopyDirectory(File srcDir, File destDir, FileFilter filter, boolean preserveFileDate, List exclusionList)@b@    throws IOException@b@  {@b@    if (destDir.exists()) {@b@      if (destDir.isDirectory()) break label98;@b@      throw new IOException("Destination '" + destDir + "' exists but is not a directory");@b@    }@b@@b@    if (!(destDir.mkdirs()))@b@      throw new IOException("Destination '" + destDir + "' directory cannot be created");@b@@b@    if (preserveFileDate) {@b@      destDir.setLastModified(srcDir.lastModified());@b@    }@b@@b@    if (!(destDir.canWrite())) {@b@      label98: throw new IOException("Destination '" + destDir + "' cannot be written to");@b@    }@b@@b@    File[] files = (filter == null) ? srcDir.listFiles() : srcDir.listFiles(filter);@b@    if (files == null)@b@      throw new IOException("Failed to list contents of " + srcDir);@b@@b@    for (int i = 0; i < files.length; ++i) {@b@      File copiedFile = new File(destDir, files[i].getName());@b@      if ((exclusionList == null) || (!(exclusionList.contains(files[i].getCanonicalPath()))))@b@        if (files[i].isDirectory())@b@          doCopyDirectory(files[i], copiedFile, filter, preserveFileDate, exclusionList);@b@        else@b@          doCopyFile(files[i], copiedFile, preserveFileDate);@b@    }@b@  }@b@@b@  public static void copyURLToFile(URL source, File destination)@b@    throws IOException@b@  {@b@    InputStream input = source.openStream();@b@    try {@b@      FileOutputStream output = openOutputStream(destination);@b@      try {@b@        IOUtils.copy(input, output);@b@      } finally {@b@        IOUtils.closeQuietly(output);@b@      }@b@    } finally {@b@      IOUtils.closeQuietly(input);@b@    }@b@  }@b@@b@  public static void deleteDirectory(File directory)@b@    throws IOException@b@  {@b@    if (!(directory.exists())) {@b@      return;@b@    }@b@@b@    cleanDirectory(directory);@b@    if (!(directory.delete())) {@b@      String message = "Unable to delete directory " + directory + ".";@b@@b@      throw new IOException(message);@b@    }@b@  }@b@@b@  public static boolean deleteQuietly(File file)@b@  {@b@    if (file == null)@b@      return false;@b@    try@b@    {@b@      if (file.isDirectory())@b@        cleanDirectory(file);@b@    }@b@    catch (Exception e)@b@    {@b@    }@b@    try {@b@      return file.delete(); } catch (Exception e) {@b@    }@b@    return false;@b@  }@b@@b@  public static void cleanDirectory(File directory)@b@    throws IOException@b@  {@b@    String message;@b@    if (!(directory.exists())) {@b@      message = directory + " does not exist";@b@      throw new IllegalArgumentException(message);@b@    }@b@@b@    if (!(directory.isDirectory())) {@b@      message = directory + " is not a directory";@b@      throw new IllegalArgumentException(message);@b@    }@b@@b@    File[] files = directory.listFiles();@b@    if (files == null) {@b@      throw new IOException("Failed to list contents of " + directory);@b@    }@b@@b@    IOException exception = null;@b@    for (int i = 0; i < files.length; ++i) {@b@      File file = files[i];@b@      try {@b@        forceDelete(file);@b@      } catch (IOException ioe) {@b@        exception = ioe;@b@      }@b@    }@b@@b@    if (null != exception)@b@      throw exception;@b@  }@b@@b@  public static boolean waitFor(File file, int seconds)@b@  {@b@    int timeout = 0;@b@    int tick = 0;@b@    if (!(file.exists())) {@b@      if (tick++ >= 10) {@b@        tick = 0;@b@        if (timeout++ > seconds)@b@          return false;@b@      }@b@      try@b@      {@b@        Thread.sleep(100L);@b@      } catch (InterruptedException ignore) {@b@      }@b@      catch (Exception ex) {@b@        break label51:@b@      }@b@    }@b@    label51: return true;@b@  }@b@@b@  public static String readFileToString(File file, String encoding)@b@    throws IOException@b@  {@b@    InputStream in = null;@b@    try {@b@      in = openInputStream(file);@b@      String str = IOUtils.toString(in, encoding);@b@@b@      return str;@b@    }@b@    finally@b@    {@b@      IOUtils.closeQuietly(in);@b@    }@b@  }@b@@b@  public static String readFileToString(File file)@b@    throws IOException@b@  {@b@    return readFileToString(file, null);@b@  }@b@@b@  public static byte[] readFileToByteArray(File file)@b@    throws IOException@b@  {@b@    InputStream in = null;@b@    try {@b@      in = openInputStream(file);@b@      byte[] arrayOfByte = IOUtils.toByteArray(in);@b@@b@      return arrayOfByte;@b@    }@b@    finally@b@    {@b@      IOUtils.closeQuietly(in);@b@    }@b@  }@b@@b@  public static List readLines(File file, String encoding)@b@    throws IOException@b@  {@b@    InputStream in = null;@b@    try {@b@      in = openInputStream(file);@b@      List localList = IOUtils.readLines(in, encoding);@b@@b@      return localList;@b@    }@b@    finally@b@    {@b@      IOUtils.closeQuietly(in);@b@    }@b@  }@b@@b@  public static List readLines(File file)@b@    throws IOException@b@  {@b@    return readLines(file, null);@b@  }@b@@b@  public static LineIterator lineIterator(File file, String encoding)@b@    throws IOException@b@  {@b@    InputStream in = null;@b@    try {@b@      in = openInputStream(file);@b@      return IOUtils.lineIterator(in, encoding);@b@    } catch (IOException ex) {@b@      IOUtils.closeQuietly(in);@b@      throw ex;@b@    } catch (RuntimeException ex) {@b@      IOUtils.closeQuietly(in);@b@      throw ex;@b@    }@b@  }@b@@b@  public static LineIterator lineIterator(File file)@b@    throws IOException@b@  {@b@    return lineIterator(file, null);@b@  }@b@@b@  public static void writeStringToFile(File file, String data, String encoding)@b@    throws IOException@b@  {@b@    OutputStream out = null;@b@    try {@b@      out = openOutputStream(file);@b@      IOUtils.write(data, out, encoding);@b@    } finally {@b@      IOUtils.closeQuietly(out);@b@    }@b@  }@b@@b@  public static void writeStringToFile(File file, String data)@b@    throws IOException@b@  {@b@    writeStringToFile(file, data, null);@b@  }@b@@b@  public static void writeByteArrayToFile(File file, byte[] data)@b@    throws IOException@b@  {@b@    OutputStream out = null;@b@    try {@b@      out = openOutputStream(file);@b@      out.write(data);@b@    } finally {@b@      IOUtils.closeQuietly(out);@b@    }@b@  }@b@@b@  public static void writeLines(File file, String encoding, Collection lines)@b@    throws IOException@b@  {@b@    writeLines(file, encoding, lines, null);@b@  }@b@@b@  public static void writeLines(File file, Collection lines)@b@    throws IOException@b@  {@b@    writeLines(file, null, lines, null);@b@  }@b@@b@  public static void writeLines(File file, String encoding, Collection lines, String lineEnding)@b@    throws IOException@b@  {@b@    OutputStream out = null;@b@    try {@b@      out = openOutputStream(file);@b@      IOUtils.writeLines(lines, lineEnding, out, encoding);@b@    } finally {@b@      IOUtils.closeQuietly(out);@b@    }@b@  }@b@@b@  public static void writeLines(File file, Collection lines, String lineEnding)@b@    throws IOException@b@  {@b@    writeLines(file, null, lines, lineEnding);@b@  }@b@@b@  public static void forceDelete(File file)@b@    throws IOException@b@  {@b@    if (file.isDirectory()) {@b@      deleteDirectory(file);@b@    } else {@b@      boolean filePresent = file.exists();@b@      if (!(file.delete())) {@b@        if (!(filePresent))@b@          throw new FileNotFoundException("File does not exist: " + file);@b@@b@        String message = "Unable to delete file: " + file;@b@@b@        throw new IOException(message);@b@      }@b@    }@b@  }@b@@b@  public static void forceDeleteOnExit(File file)@b@    throws IOException@b@  {@b@    if (file.isDirectory())@b@      deleteDirectoryOnExit(file);@b@    else@b@      file.deleteOnExit();@b@  }@b@@b@  private static void deleteDirectoryOnExit(File directory)@b@    throws IOException@b@  {@b@    if (!(directory.exists())) {@b@      return;@b@    }@b@@b@    cleanDirectoryOnExit(directory);@b@    directory.deleteOnExit();@b@  }@b@@b@  private static void cleanDirectoryOnExit(File directory)@b@    throws IOException@b@  {@b@    String message;@b@    if (!(directory.exists())) {@b@      message = directory + " does not exist";@b@      throw new IllegalArgumentException(message);@b@    }@b@@b@    if (!(directory.isDirectory())) {@b@      message = directory + " is not a directory";@b@      throw new IllegalArgumentException(message);@b@    }@b@@b@    File[] files = directory.listFiles();@b@    if (files == null) {@b@      throw new IOException("Failed to list contents of " + directory);@b@    }@b@@b@    IOException exception = null;@b@    for (int i = 0; i < files.length; ++i) {@b@      File file = files[i];@b@      try {@b@        forceDeleteOnExit(file);@b@      } catch (IOException ioe) {@b@        exception = ioe;@b@      }@b@    }@b@@b@    if (null != exception)@b@      throw exception;@b@  }@b@@b@  public static void forceMkdir(File directory)@b@    throws IOException@b@  {@b@    String message;@b@    if (directory.exists()) {@b@      if (!(directory.isFile())) return;@b@      message = "File " + directory + " exists and is " + "not a directory. Unable to create directory.";@b@@b@      throw new IOException(message);@b@    }@b@@b@    if (!(directory.mkdirs())) {@b@      message = "Unable to create directory " + directory;@b@@b@      throw new IOException(message);@b@    }@b@  }@b@@b@  public static long sizeOfDirectory(File directory)@b@  {@b@    String message;@b@    if (!(directory.exists())) {@b@      message = directory + " does not exist";@b@      throw new IllegalArgumentException(message);@b@    }@b@@b@    if (!(directory.isDirectory())) {@b@      message = directory + " is not a directory";@b@      throw new IllegalArgumentException(message);@b@    }@b@@b@    long size = 0L;@b@@b@    File[] files = directory.listFiles();@b@    if (files == null)@b@      return 0L;@b@@b@    for (int i = 0; i < files.length; ++i) {@b@      File file = files[i];@b@@b@      if (file.isDirectory())@b@        size += sizeOfDirectory(file);@b@      else@b@        size += file.length();@b@@b@    }@b@@b@    return size;@b@  }@b@@b@  public static boolean isFileNewer(File file, File reference)@b@  {@b@    if (reference == null)@b@      throw new IllegalArgumentException("No specified reference file");@b@@b@    if (!(reference.exists())) {@b@      throw new IllegalArgumentException("The reference file '" + file + "' doesn't exist");@b@    }@b@@b@    return isFileNewer(file, reference.lastModified());@b@  }@b@@b@  public static boolean isFileNewer(File file, Date date)@b@  {@b@    if (date == null)@b@      throw new IllegalArgumentException("No specified date");@b@@b@    return isFileNewer(file, date.getTime());@b@  }@b@@b@  public static boolean isFileNewer(File file, long timeMillis)@b@  {@b@    if (file == null)@b@      throw new IllegalArgumentException("No specified file");@b@@b@    if (!(file.exists()))@b@      return false;@b@@b@    return (file.lastModified() > timeMillis);@b@  }@b@@b@  public static boolean isFileOlder(File file, File reference)@b@  {@b@    if (reference == null)@b@      throw new IllegalArgumentException("No specified reference file");@b@@b@    if (!(reference.exists())) {@b@      throw new IllegalArgumentException("The reference file '" + file + "' doesn't exist");@b@    }@b@@b@    return isFileOlder(file, reference.lastModified());@b@  }@b@@b@  public static boolean isFileOlder(File file, Date date)@b@  {@b@    if (date == null)@b@      throw new IllegalArgumentException("No specified date");@b@@b@    return isFileOlder(file, date.getTime());@b@  }@b@@b@  public static boolean isFileOlder(File file, long timeMillis)@b@  {@b@    if (file == null)@b@      throw new IllegalArgumentException("No specified file");@b@@b@    if (!(file.exists()))@b@      return false;@b@@b@    return (file.lastModified() < timeMillis);@b@  }@b@@b@  public static long checksumCRC32(File file)@b@    throws IOException@b@  {@b@    CRC32 crc = new CRC32();@b@    checksum(file, crc);@b@    return crc.getValue();@b@  }@b@@b@  public static Checksum checksum(File file, Checksum checksum)@b@    throws IOException@b@  {@b@    if (file.isDirectory())@b@      throw new IllegalArgumentException("Checksums can't be computed on directories");@b@@b@    InputStream in = null;@b@    try {@b@      in = new CheckedInputStream(new FileInputStream(file), checksum);@b@      IOUtils.copy(in, new NullOutputStream());@b@    } finally {@b@      IOUtils.closeQuietly(in);@b@    }@b@    return checksum;@b@  }@b@@b@  public static void moveDirectory(File srcDir, File destDir)@b@    throws IOException@b@  {@b@    if (srcDir == null)@b@      throw new NullPointerException("Source must not be null");@b@@b@    if (destDir == null)@b@      throw new NullPointerException("Destination must not be null");@b@@b@    if (!(srcDir.exists()))@b@      throw new FileNotFoundException("Source '" + srcDir + "' does not exist");@b@@b@    if (!(srcDir.isDirectory()))@b@      throw new IOException("Source '" + srcDir + "' is not a directory");@b@@b@    if (destDir.exists())@b@      throw new IOException("Destination '" + destDir + "' already exists");@b@@b@    boolean rename = srcDir.renameTo(destDir);@b@    if (!(rename)) {@b@      copyDirectory(srcDir, destDir);@b@      deleteDirectory(srcDir);@b@      if (srcDir.exists())@b@        throw new IOException("Failed to delete original directory '" + srcDir + "' after copy to '" + destDir + "'");@b@    }@b@  }@b@@b@  public static void moveDirectoryToDirectory(File src, File destDir, boolean createDestDir)@b@    throws IOException@b@  {@b@    if (src == null)@b@      throw new NullPointerException("Source must not be null");@b@@b@    if (destDir == null)@b@      throw new NullPointerException("Destination directory must not be null");@b@@b@    if ((!(destDir.exists())) && (createDestDir))@b@      destDir.mkdirs();@b@@b@    if (!(destDir.exists())) {@b@      throw new FileNotFoundException("Destination directory '" + destDir + "' does not exist [createDestDir=" + createDestDir + "]");@b@    }@b@@b@    if (!(destDir.isDirectory()))@b@      throw new IOException("Destination '" + destDir + "' is not a directory");@b@@b@    moveDirectory(src, new File(destDir, src.getName()));@b@  }@b@@b@  public static void moveFile(File srcFile, File destFile)@b@    throws IOException@b@  {@b@    if (srcFile == null)@b@      throw new NullPointerException("Source must not be null");@b@@b@    if (destFile == null)@b@      throw new NullPointerException("Destination must not be null");@b@@b@    if (!(srcFile.exists()))@b@      throw new FileNotFoundException("Source '" + srcFile + "' does not exist");@b@@b@    if (srcFile.isDirectory())@b@      throw new IOException("Source '" + srcFile + "' is a directory");@b@@b@    if (destFile.exists())@b@      throw new IOException("Destination '" + destFile + "' already exists");@b@@b@    if (destFile.isDirectory())@b@      throw new IOException("Destination '" + destFile + "' is a directory");@b@@b@    boolean rename = srcFile.renameTo(destFile);@b@    if (!(rename)) {@b@      copyFile(srcFile, destFile);@b@      if (!(srcFile.delete())) {@b@        deleteQuietly(destFile);@b@        throw new IOException("Failed to delete original file '" + srcFile + "' after copy to '" + destFile + "'");@b@      }@b@    }@b@  }@b@@b@  public static void moveFileToDirectory(File srcFile, File destDir, boolean createDestDir)@b@    throws IOException@b@  {@b@    if (srcFile == null)@b@      throw new NullPointerException("Source must not be null");@b@@b@    if (destDir == null)@b@      throw new NullPointerException("Destination directory must not be null");@b@@b@    if ((!(destDir.exists())) && (createDestDir))@b@      destDir.mkdirs();@b@@b@    if (!(destDir.exists())) {@b@      throw new FileNotFoundException("Destination directory '" + destDir + "' does not exist [createDestDir=" + createDestDir + "]");@b@    }@b@@b@    if (!(destDir.isDirectory()))@b@      throw new IOException("Destination '" + destDir + "' is not a directory");@b@@b@    moveFile(srcFile, new File(destDir, srcFile.getName()));@b@  }@b@@b@  public static void moveToDirectory(File src, File destDir, boolean createDestDir)@b@    throws IOException@b@  {@b@    if (src == null)@b@      throw new NullPointerException("Source must not be null");@b@@b@    if (destDir == null)@b@      throw new NullPointerException("Destination must not be null");@b@@b@    if (!(src.exists()))@b@      throw new FileNotFoundException("Source '" + src + "' does not exist");@b@@b@    if (src.isDirectory())@b@      moveDirectoryToDirectory(src, destDir, createDestDir);@b@    else@b@      moveFileToDirectory(src, destDir, createDestDir);@b@  }@b@}

2.IOUtils依赖工具类

package org.apache.commons.io;@b@@b@import java.io.BufferedInputStream;@b@import java.io.BufferedReader;@b@import java.io.ByteArrayInputStream;@b@import java.io.CharArrayWriter;@b@import java.io.File;@b@import java.io.IOException;@b@import java.io.InputStream;@b@import java.io.InputStreamReader;@b@import java.io.OutputStream;@b@import java.io.OutputStreamWriter;@b@import java.io.PrintWriter;@b@import java.io.Reader;@b@import java.io.StringWriter;@b@import java.io.Writer;@b@import java.util.ArrayList;@b@import java.util.Collection;@b@import java.util.Iterator;@b@import java.util.List;@b@import org.apache.commons.io.output.ByteArrayOutputStream;@b@@b@public class IOUtils@b@{@b@  public static final char DIR_SEPARATOR_UNIX = 47;@b@  public static final char DIR_SEPARATOR_WINDOWS = 92;@b@  public static final char DIR_SEPARATOR = File.separatorChar;@b@  public static final String LINE_SEPARATOR_UNIX = "\n";@b@  public static final String LINE_SEPARATOR_WINDOWS = "\r\n";@b@  public static final String LINE_SEPARATOR;@b@  private static final int DEFAULT_BUFFER_SIZE = 4096;@b@@b@  public static void closeQuietly(Reader input)@b@  {@b@    try@b@    {@b@      if (input != null)@b@        input.close();@b@    }@b@    catch (IOException ioe)@b@    {@b@    }@b@  }@b@@b@  public static void closeQuietly(Writer output)@b@  {@b@    try@b@    {@b@      if (output != null)@b@        output.close();@b@    }@b@    catch (IOException ioe)@b@    {@b@    }@b@  }@b@@b@  public static void closeQuietly(InputStream input)@b@  {@b@    try@b@    {@b@      if (input != null)@b@        input.close();@b@    }@b@    catch (IOException ioe)@b@    {@b@    }@b@  }@b@@b@  public static void closeQuietly(OutputStream output)@b@  {@b@    try@b@    {@b@      if (output != null)@b@        output.close();@b@    }@b@    catch (IOException ioe)@b@    {@b@    }@b@  }@b@@b@  public static byte[] toByteArray(InputStream input)@b@    throws IOException@b@  {@b@    ByteArrayOutputStream output = new ByteArrayOutputStream();@b@    copy(input, output);@b@    return output.toByteArray();@b@  }@b@@b@  public static byte[] toByteArray(Reader input)@b@    throws IOException@b@  {@b@    ByteArrayOutputStream output = new ByteArrayOutputStream();@b@    copy(input, output);@b@    return output.toByteArray();@b@  }@b@@b@  public static byte[] toByteArray(Reader input, String encoding)@b@    throws IOException@b@  {@b@    ByteArrayOutputStream output = new ByteArrayOutputStream();@b@    copy(input, output, encoding);@b@    return output.toByteArray();@b@  }@b@@b@  /**@b@   * @deprecated@b@   */@b@  public static byte[] toByteArray(String input)@b@    throws IOException@b@  {@b@    return input.getBytes();@b@  }@b@@b@  public static char[] toCharArray(InputStream is)@b@    throws IOException@b@  {@b@    CharArrayWriter output = new CharArrayWriter();@b@    copy(is, output);@b@    return output.toCharArray();@b@  }@b@@b@  public static char[] toCharArray(InputStream is, String encoding)@b@    throws IOException@b@  {@b@    CharArrayWriter output = new CharArrayWriter();@b@    copy(is, output, encoding);@b@    return output.toCharArray();@b@  }@b@@b@  public static char[] toCharArray(Reader input)@b@    throws IOException@b@  {@b@    CharArrayWriter sw = new CharArrayWriter();@b@    copy(input, sw);@b@    return sw.toCharArray();@b@  }@b@@b@  public static String toString(InputStream input)@b@    throws IOException@b@  {@b@    StringWriter sw = new StringWriter();@b@    copy(input, sw);@b@    return sw.toString();@b@  }@b@@b@  public static String toString(InputStream input, String encoding)@b@    throws IOException@b@  {@b@    StringWriter sw = new StringWriter();@b@    copy(input, sw, encoding);@b@    return sw.toString();@b@  }@b@@b@  public static String toString(Reader input)@b@    throws IOException@b@  {@b@    StringWriter sw = new StringWriter();@b@    copy(input, sw);@b@    return sw.toString();@b@  }@b@@b@  /**@b@   * @deprecated@b@   */@b@  public static String toString(byte[] input)@b@    throws IOException@b@  {@b@    return new String(input);@b@  }@b@@b@  /**@b@   * @deprecated@b@   */@b@  public static String toString(byte[] input, String encoding)@b@    throws IOException@b@  {@b@    if (encoding == null)@b@      return new String(input);@b@@b@    return new String(input, encoding);@b@  }@b@@b@  public static List readLines(InputStream input)@b@    throws IOException@b@  {@b@    InputStreamReader reader = new InputStreamReader(input);@b@    return readLines(reader);@b@  }@b@@b@  public static List readLines(InputStream input, String encoding)@b@    throws IOException@b@  {@b@    if (encoding == null)@b@      return readLines(input);@b@@b@    InputStreamReader reader = new InputStreamReader(input, encoding);@b@    return readLines(reader);@b@  }@b@@b@  public static List readLines(Reader input)@b@    throws IOException@b@  {@b@    BufferedReader reader = new BufferedReader(input);@b@    List list = new ArrayList();@b@    String line = reader.readLine();@b@    while (line != null) {@b@      list.add(line);@b@      line = reader.readLine();@b@    }@b@    return list;@b@  }@b@@b@  public static LineIterator lineIterator(Reader reader)@b@  {@b@    return new LineIterator(reader);@b@  }@b@@b@  public static LineIterator lineIterator(InputStream input, String encoding)@b@    throws IOException@b@  {@b@    Reader reader = null;@b@    if (encoding == null)@b@      reader = new InputStreamReader(input);@b@    else@b@      reader = new InputStreamReader(input, encoding);@b@@b@    return new LineIterator(reader);@b@  }@b@@b@  public static InputStream toInputStream(String input)@b@  {@b@    byte[] bytes = input.getBytes();@b@    return new ByteArrayInputStream(bytes);@b@  }@b@@b@  public static InputStream toInputStream(String input, String encoding)@b@    throws IOException@b@  {@b@    byte[] bytes = (encoding != null) ? input.getBytes(encoding) : input.getBytes();@b@    return new ByteArrayInputStream(bytes);@b@  }@b@@b@  public static void write(byte[] data, OutputStream output)@b@    throws IOException@b@  {@b@    if (data != null)@b@      output.write(data);@b@  }@b@@b@  public static void write(byte[] data, Writer output)@b@    throws IOException@b@  {@b@    if (data != null)@b@      output.write(new String(data));@b@  }@b@@b@  public static void write(byte[] data, Writer output, String encoding)@b@    throws IOException@b@  {@b@    if (data != null)@b@      if (encoding == null)@b@        write(data, output);@b@      else@b@        output.write(new String(data, encoding));@b@  }@b@@b@  public static void write(char[] data, Writer output)@b@    throws IOException@b@  {@b@    if (data != null)@b@      output.write(data);@b@  }@b@@b@  public static void write(char[] data, OutputStream output)@b@    throws IOException@b@  {@b@    if (data != null)@b@      output.write(new String(data).getBytes());@b@  }@b@@b@  public static void write(char[] data, OutputStream output, String encoding)@b@    throws IOException@b@  {@b@    if (data != null)@b@      if (encoding == null)@b@        write(data, output);@b@      else@b@        output.write(new String(data).getBytes(encoding));@b@  }@b@@b@  public static void write(String data, Writer output)@b@    throws IOException@b@  {@b@    if (data != null)@b@      output.write(data);@b@  }@b@@b@  public static void write(String data, OutputStream output)@b@    throws IOException@b@  {@b@    if (data != null)@b@      output.write(data.getBytes());@b@  }@b@@b@  public static void write(String data, OutputStream output, String encoding)@b@    throws IOException@b@  {@b@    if (data != null)@b@      if (encoding == null)@b@        write(data, output);@b@      else@b@        output.write(data.getBytes(encoding));@b@  }@b@@b@  public static void write(StringBuffer data, Writer output)@b@    throws IOException@b@  {@b@    if (data != null)@b@      output.write(data.toString());@b@  }@b@@b@  public static void write(StringBuffer data, OutputStream output)@b@    throws IOException@b@  {@b@    if (data != null)@b@      output.write(data.toString().getBytes());@b@  }@b@@b@  public static void write(StringBuffer data, OutputStream output, String encoding)@b@    throws IOException@b@  {@b@    if (data != null)@b@      if (encoding == null)@b@        write(data, output);@b@      else@b@        output.write(data.toString().getBytes(encoding));@b@  }@b@@b@  public static void writeLines(Collection lines, String lineEnding, OutputStream output)@b@    throws IOException@b@  {@b@    if (lines == null)@b@      return;@b@@b@    if (lineEnding == null)@b@      lineEnding = LINE_SEPARATOR;@b@@b@    for (Iterator it = lines.iterator(); it.hasNext(); ) {@b@      Object line = it.next();@b@      if (line != null)@b@        output.write(line.toString().getBytes());@b@@b@      output.write(lineEnding.getBytes());@b@    }@b@  }@b@@b@  public static void writeLines(Collection lines, String lineEnding, OutputStream output, String encoding)@b@    throws IOException@b@  {@b@    Iterator it;@b@    if (encoding == null) {@b@      writeLines(lines, lineEnding, output);@b@    } else {@b@      if (lines == null)@b@        return;@b@@b@      if (lineEnding == null)@b@        lineEnding = LINE_SEPARATOR;@b@@b@      for (it = lines.iterator(); it.hasNext(); ) {@b@        Object line = it.next();@b@        if (line != null)@b@          output.write(line.toString().getBytes(encoding));@b@@b@        output.write(lineEnding.getBytes(encoding));@b@      }@b@    }@b@  }@b@@b@  public static void writeLines(Collection lines, String lineEnding, Writer writer)@b@    throws IOException@b@  {@b@    if (lines == null)@b@      return;@b@@b@    if (lineEnding == null)@b@      lineEnding = LINE_SEPARATOR;@b@@b@    for (Iterator it = lines.iterator(); it.hasNext(); ) {@b@      Object line = it.next();@b@      if (line != null)@b@        writer.write(line.toString());@b@@b@      writer.write(lineEnding);@b@    }@b@  }@b@@b@  public static int copy(InputStream input, OutputStream output)@b@    throws IOException@b@  {@b@    long count = copyLarge(input, output);@b@    if (count > 2147483647L)@b@      return -1;@b@@b@    return (int)count;@b@  }@b@@b@  public static long copyLarge(InputStream input, OutputStream output)@b@    throws IOException@b@  {@b@    byte[] buffer = new byte[4096];@b@    long count = 0L;@b@    int n = 0;@b@    while (-1 != (n = input.read(buffer))) {@b@      output.write(buffer, 0, n);@b@      count += n;@b@    }@b@    return count;@b@  }@b@@b@  public static void copy(InputStream input, Writer output)@b@    throws IOException@b@  {@b@    InputStreamReader in = new InputStreamReader(input);@b@    copy(in, output);@b@  }@b@@b@  public static void copy(InputStream input, Writer output, String encoding)@b@    throws IOException@b@  {@b@    if (encoding == null) {@b@      copy(input, output);@b@    } else {@b@      InputStreamReader in = new InputStreamReader(input, encoding);@b@      copy(in, output);@b@    }@b@  }@b@@b@  public static int copy(Reader input, Writer output)@b@    throws IOException@b@  {@b@    long count = copyLarge(input, output);@b@    if (count > 2147483647L)@b@      return -1;@b@@b@    return (int)count;@b@  }@b@@b@  public static long copyLarge(Reader input, Writer output)@b@    throws IOException@b@  {@b@    char[] buffer = new char[4096];@b@    long count = 0L;@b@    int n = 0;@b@    while (-1 != (n = input.read(buffer))) {@b@      output.write(buffer, 0, n);@b@      count += n;@b@    }@b@    return count;@b@  }@b@@b@  public static void copy(Reader input, OutputStream output)@b@    throws IOException@b@  {@b@    OutputStreamWriter out = new OutputStreamWriter(output);@b@    copy(input, out);@b@@b@    out.flush();@b@  }@b@@b@  public static void copy(Reader input, OutputStream output, String encoding)@b@    throws IOException@b@  {@b@    if (encoding == null) {@b@      copy(input, output);@b@    } else {@b@      OutputStreamWriter out = new OutputStreamWriter(output, encoding);@b@      copy(input, out);@b@@b@      out.flush();@b@    }@b@  }@b@@b@  public static boolean contentEquals(InputStream input1, InputStream input2)@b@    throws IOException@b@  {@b@    if (!(input1 instanceof BufferedInputStream))@b@      input1 = new BufferedInputStream(input1);@b@@b@    if (!(input2 instanceof BufferedInputStream)) {@b@      input2 = new BufferedInputStream(input2);@b@    }@b@@b@    int ch = input1.read();@b@    while (-1 != ch) {@b@      ch2 = input2.read();@b@      if (ch != ch2)@b@        return false;@b@@b@      ch = input1.read();@b@    }@b@@b@    int ch2 = input2.read();@b@    return (ch2 == -1);@b@  }@b@@b@  public static boolean contentEquals(Reader input1, Reader input2)@b@    throws IOException@b@  {@b@    if (!(input1 instanceof BufferedReader))@b@      input1 = new BufferedReader(input1);@b@@b@    if (!(input2 instanceof BufferedReader)) {@b@      input2 = new BufferedReader(input2);@b@    }@b@@b@    int ch = input1.read();@b@    while (-1 != ch) {@b@      ch2 = input2.read();@b@      if (ch != ch2)@b@        return false;@b@@b@      ch = input1.read();@b@    }@b@@b@    int ch2 = input2.read();@b@    return (ch2 == -1);@b@  }@b@@b@  static@b@  {@b@    StringWriter buf = new StringWriter(4);@b@    PrintWriter out = new PrintWriter(buf);@b@    out.println();@b@    LINE_SEPARATOR = buf.toString();@b@  }@b@}