含有压缩等最全功能的文件及文件夹处理工具类FileUtil

含有压缩等最全功能的文件及文件夹处理工具类

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class FileUtil
{
  private static final Logger log = LoggerFactory.getLogger(FileUtil.class);

  public static int getDirFileCount(String dir)
  {
    File f = new File(dir);
    return f.listFiles().length;
  }

  public static void compress(String srcFilePath, String destFilePath)
  {
    File src = new File(srcFilePath);

    if (!src.exists()) {
      throw new RuntimeException(srcFilePath + "不存在");
    }
    File zipFile = new File(destFilePath);
    try
    {
      FileOutputStream fos = new FileOutputStream(zipFile);
      ZipOutputStream zos = new ZipOutputStream(fos);
      String baseDir = "";
      compressByType(src, zos, baseDir);
      zos.close();
    }
    catch (Exception e)
    {
      e.printStackTrace();
    }
  }

  public static void compress(ConcurrentLinkedQueue<File> files, String zipFilePath)
  {
    File zipFile = new File(zipFilePath);
    try {
      ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFile));

      while (!files.isEmpty()) {
        File file = (File)files.poll();
        compressByType(file, zos, "");
      }
      zos.close();
      log.info("compressed {} files success!", Integer.valueOf(files.size()));
    } catch (Exception e) {
      log.error(e.getMessage(), e);
    }
  }

  private static void compressByType(File src, ZipOutputStream zos, String baseDir)
  {
    if (!src.exists())
      return;
    System.out.println("压缩路径" + baseDir + src.getName());

    if (src.isFile())
    {
      compressFile(src, zos, baseDir);
    } else if (src.isDirectory())
    {
      compressDir(src, zos, baseDir);
    }
  }

  private static void compressFile(File file, ZipOutputStream zos, String baseDir)
  {
    if (!file.exists())
      return;
    try {
      BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
      ZipEntry entry = new ZipEntry(baseDir + file.getName());
      zos.putNextEntry(entry);

      byte[] buf = new byte[1024];
      int count;
      while ((count = bis.read(buf)) != -1) {
        zos.write(buf, 0, count);
      }
      bis.close();
      copyBackFile(file, file.getName(), SynFile.oldPath);
      deleteFile(file);
    } catch (Exception e) {
      log.error(e.getMessage(), e);
    }
  }

  private static void compressDir(File dir, ZipOutputStream zos, String baseDir)
  {
    if (!dir.exists())
      return;
    File[] files = dir.listFiles();
    if (files.length == 0) {
      try {
        zos.putNextEntry(new ZipEntry(baseDir + dir.getName() + File.separator));
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
    for (File file : files)
      compressByType(file, zos, baseDir + dir.getName() + File.separator);
  }

  public static void copyBackFile(File f, String fileName, String toPath)
  {
    log.info("fileName获得的文件名为:{}", fileName);
    String targetDir = "";
    if (!fileName.contains("_")) {
      log.error("**********该文件 {} 没有时间戳**********", fileName);
      SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
      targetDir = toPath + "undefine/" + sdf.format(new Date()) + "/";
    } else {
      int ind = fileName.lastIndexOf("_");
      String fileDate = fileName.substring(ind + 1, ind + 1 + 8);
      targetDir = toPath + fileDate + "/";
    }

    File targetDirF = new File(targetDir);
    if ((!targetDirF.exists()) || (!targetDirF.isDirectory())) {
      targetDirF.mkdir();
    }
    File targetFile = new File(targetDir + fileName);
    if (targetFile.exists()) {
      targetFile.delete();
    }
    copy(f, targetFile);
  }

  public static void deleteFile(File file)
  {
    if (file.isDirectory()) {
      return;
    }
    if (!file.exists()) {
      return;
    }
    if (!file.delete())
      return;
  }

  public static String readFile(InputStream is)
  {
    BufferedReader br = null;
    StringBuffer sb = new StringBuffer();
    try {
      br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
      String readLine = null;
      while ((readLine = br.readLine()) != null)
        sb.append(readLine);
    }
    catch (Exception e) {
      e.printStackTrace();
    } finally {
      try {
        br.close();
        is.close();
      } catch (IOException e) {
        e.printStackTrace();
        if (log.isErrorEnabled()) {
          log.error(e.getMessage(), e);
        }
      }
    }
    return sb.toString();
  }

  public static boolean isFileExist(String fileName)
  {
    return new File(fileName).isFile();
  }

  public static boolean makeDirectory(File file)
  {
    File parent = file.getParentFile();
    if (parent != null) {
      return parent.mkdirs();
    }
    return false;
  }

  public static URL getURL(File file)
    throws MalformedURLException
  {
    String fileURL = "file:/" + file.getAbsolutePath();
    URL url = new URL(fileURL);
    return url;
  }

  public static String getFileName(String filePath)
  {
    File file = new File(filePath);
    return file.getName();
  }

  public static String getFilePath(String fileName)
  {
    File file = new File(fileName);
    return file.getAbsolutePath();
  }

  public static String toUNIXpath(String filePath)
  {
    return filePath.replace("", "/");
  }

  public static String getUNIXfilePath(String fileName)
  {
    File file = new File(fileName);
    return toUNIXpath(file.getAbsolutePath());
  }

  public static String getFileExt(String fileName)
  {
    int point = fileName.lastIndexOf('.');
    int length = fileName.length();
    if ((point == -1) || (point == length - 1)) {
      return "";
    }
    return fileName.substring(point + 1, length);
  }

  public static String getNamePart(String fileName)
  {
    int point = getPathLastIndex(fileName);
    int length = fileName.length();
    if (point == -1)
      return fileName;
    if (point == length - 1) {
      int secondPoint = getPathLastIndex(fileName, point - 1);
      if (secondPoint == -1) {
        if (length == 1) {
          return fileName;
        }
        return fileName.substring(0, point);
      }

      return fileName.substring(secondPoint + 1, point);
    }

    return fileName.substring(point + 1);
  }

  public static String getPathPart(String fileName)
  {
    int point = getPathLastIndex(fileName);
    int length = fileName.length();
    if (point == -1)
      return "";
    if (point == length - 1) {
      int secondPoint = getPathLastIndex(fileName, point - 1);
      if (secondPoint == -1) {
        return "";
      }
      return fileName.substring(0, secondPoint);
    }

    return fileName.substring(0, point);
  }

  public static int getPathLastIndex(String fileName)
  {
    int point = fileName.lastIndexOf("/");
    if (point == -1) {
      point = fileName.lastIndexOf("");
    }
    return point;
  }

  public static int getPathLastIndex(String fileName, int fromIndex)
  {
    int point = fileName.lastIndexOf("/", fromIndex);
    if (point == -1) {
      point = fileName.lastIndexOf("", fromIndex);
    }
    return point;
  }

  public static int getPathIndex(String fileName)
  {
    int point = fileName.indexOf("/");
    if (point == -1) {
      point = fileName.indexOf("");
    }
    return point;
  }

  public static int getPathIndex(String fileName, int fromIndex)
  {
    int point = fileName.indexOf("/", fromIndex);
    if (point == -1) {
      point = fileName.indexOf("", fromIndex);
    }
    return point;
  }

  public static String removeFileExt(String filename)
  {
    int index = filename.lastIndexOf(".");
    if (index != -1) {
      return filename.substring(0, index);
    }
    return filename;
  }

  public static String getSubpath(String pathName, String fileName)
  {
    int index = fileName.indexOf(pathName);
    if (index != -1) {
      return fileName.substring(index + pathName.length() + 1);
    }
    return fileName;
  }

  public static void deleteFile(String filename)
  {
    File file = new File(filename);
    if (file.isDirectory()) {
      return;
    }
    if (!file.exists()) {
      return;
    }
    if (!file.delete())
      return;
  }

  public static void deleteDir(File dir, boolean delParent)
    throws IOException
  {
    if (dir.isFile())
      throw new IOException("IOException -> BadInputException: not a directory.");
    File[] files = dir.listFiles();
    if (files != null) {
      for (int i = 0; i < files.length; i++) {
        File file = files[i];
        if (file.isFile())
          file.delete();
        else {
          deleteDir(file, true);
        }
      }
    }
    if (delParent)
      dir.delete();
  }

  public static void copy(File src, File dst)
  {
    int BUFFER_SIZE = 4096;
    InputStream in = null;
    OutputStream out = null;
    try {
      in = new BufferedInputStream(new FileInputStream(src), BUFFER_SIZE);
      out = new BufferedOutputStream(new FileOutputStream(dst), BUFFER_SIZE);
      byte[] buffer = new byte[BUFFER_SIZE];
      int len = 0;
      while ((len = in.read(buffer)) > 0) {
        out.write(buffer, 0, len);
      }

      if (null != in) {
        try {
          in.close();
        } catch (IOException e) {
          e.printStackTrace();
          if (log.isErrorEnabled()) {
            log.error(e.getMessage(), e);
          }
        }
        in = null;
      }
      if (null != out) {
        try {
          out.close();
        } catch (IOException e) {
          e.printStackTrace();
          if (log.isErrorEnabled()) {
            log.error(e.getMessage(), e);
          }
        }
        out = null;
      }
    }
    catch (Exception e)
    {
      if (log.isErrorEnabled()) {
        log.error("复制文件出现异常! {}", e.getMessage(), e);
      }

      if (null != in) {
        try {
          in.close();
        } catch (IOException e) {
          e.printStackTrace();
          if (log.isErrorEnabled()) {
            log.error(e.getMessage(), e);
          }
        }
        in = null;
      }
      if (null != out) {
        try {
          out.close();
        } catch (IOException e) {
          e.printStackTrace();
          if (log.isErrorEnabled()) {
            log.error(e.getMessage(), e);
          }
        }
        out = null;
      }
    }
    finally
    {
      if (null != in) {
        try {
          in.close();
        } catch (IOException e) {
          e.printStackTrace();
          if (log.isErrorEnabled()) {
            log.error(e.getMessage(), e);
          }
        }
        in = null;
      }
      if (null != out) {
        try {
          out.close();
        } catch (IOException e) {
          e.printStackTrace();
          if (log.isErrorEnabled()) {
            log.error(e.getMessage(), e);
          }
        }
        out = null;
      }
    }
  }

  public static void copy(File src, File dst, boolean append)
    throws Exception
  {
    int BUFFER_SIZE = 4096;
    InputStream in = null;
    OutputStream out = null;
    try {
      in = new BufferedInputStream(new FileInputStream(src), BUFFER_SIZE);
      out = new BufferedOutputStream(new FileOutputStream(dst, append), BUFFER_SIZE);
      byte[] buffer = new byte[BUFFER_SIZE];
      int len = 0;
      while ((len = in.read(buffer)) > 0) {
        out.write(buffer, 0, len);
      }

      if (null != in) {
        try {
          in.close();
        } catch (IOException e) {
          e.printStackTrace();
          if (log.isErrorEnabled()) {
            log.error(e.getMessage(), e);
          }
        }
        in = null;
      }
      if (null != out) {
        try {
          out.close();
        } catch (IOException e) {
          e.printStackTrace();
          if (log.isErrorEnabled()) {
            log.error(e.getMessage(), e);
          }
        }
        out = null;
      }
    }
    catch (Exception e)
    {
      throw e;
    } finally {
      if (null != in) {
        try {
          in.close();
        } catch (IOException e) {
          e.printStackTrace();
          if (log.isErrorEnabled()) {
            log.error(e.getMessage(), e);
          }
        }
        in = null;
      }
      if (null != out) {
        try {
          out.close();
        } catch (IOException e) {
          e.printStackTrace();
          if (log.isErrorEnabled()) {
            log.error(e.getMessage(), e);
          }
        }
        out = null;
      }
    }
  }
}
发布了160 篇原创文章 · 获赞 25 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/as4589sd/article/details/104513464
今日推荐