文件工具类

/**

  • @author chenxiaoyang

  • @description:

  • @dATE:2021/3/26 15:42
    */
    public class FileUtils {

    private static Logger log = LoggerFactory.getLogger(FileUtils.class);

    /**

    • 修改程序。
    • 内部递归调用,进行子目录的更名
    • @param path 路径
    • @param from 原始的后缀名,包括那个(.点)
    • @param to 改名的后缀,也包括那个(.点)
      */
      public static void reName(String path, String from, String to) {
      File f = new File(path);
      String name = f.getName();
      if (name.endsWith(from)) {
      f.renameTo(new File(f.getParent() + “/” + name.substring(0, name.indexOf(from)) + to));
      }
      }

    /**

    • 指定路径如果没有则创建并添加
    • @param strPath
      */
      public static void createPath(String strPath) {
      //指定路径如果没有则创建并添加
      File file = new File(strPath);
      // 判断是否存在
      if (!file.exists()) {
      //创建父目录文件
      file.mkdirs();
      }
      }

    /**

    • @param filePath
    • @return
    • @description 读取文件
      */
      public static File[] getList(String filePath) throws Exception {
      try {
      FileUtils.createPath(filePath);
      File file = new File(filePath);
      File[] xlsxList = file.listFiles((dir, name) -> name.endsWith(“.xlsx”) || name.endsWith(“.xls”));
      if (xlsxList == null || xlsxList.length <= 0) return null;
      return xlsxList;
      } catch (Exception e) {
      log.error(“读取文件【{}】错误:{}”, filePath, e);
      throw new Exception(“读取” + filePath + “错误”, e);
      }
      }

    /**

    • 将bytes写入本地文件
    • @param filePath
    • @param in
    • @throws java.io.IOException
      */
      public static void writeToLocal(String filePath, ByteArrayInputStream in, String fileName) throws Exception {
      createPath(filePath);
      try (FileOutputStream downloadFile = new FileOutputStream(new File(filePath + fileName))) {
      byte[] buff = new byte[1024];
      int rc = 0;
      while ((rc = in.read(buff, 0, 1024)) > 0) {
      downloadFile.write(buff, 0, rc);
      }
      downloadFile.flush();
      } catch (Exception e) {
      log.error(“写入文件【{}】错误:{}”, filePath, e);
      throw new Exception(“写入文件” + filePath + “错误”, e);
      } finally {
      in.close();
      }
      }

    /**

    • 将bytes写入本地文件
    • @param filePath
    • @param in
    • @throws java.io.IOException
      */
      public static void writeGzipToLocal(String filePath, ByteArrayInputStream in, String fileName) throws Exception {
      createPath(filePath);
      ZipOutputStream zipOut = null;
      try (FileOutputStream downloadFile = new FileOutputStream(new File(filePath + fileName))) {
      //创建压缩输出流
      zipOut = new ZipOutputStream(downloadFile);
      zipOut.putNextEntry(new ZipEntry(fileName));
      int temp = 0;
      while ((temp = in.read()) != -1) {
      zipOut.write(temp); // 压缩输出
      }
      // 关闭流
      in.close();
      zipOut.close();
      } catch (Exception e) {
      log.error(“写入文件【{}】错误:{}”, filePath, e);
      throw new Exception(“写入文件” + filePath + “错误”, e);
      } finally {
      in.close();
      zipOut.close();
      }
      }

    public static byte[] getContent(String filePath) {
    try (FileInputStream fi = new FileInputStream(new File(filePath))) {
    int length = fi.available();
    byte[] data = new byte[length];
    fi.read(data);
    return data;
    } catch (Exception e) {
    log.error(“读取文件:{}失败:{}”, filePath, e);
    return null;
    }
    }

    /**

    • 将存放在sourceFilePath目录下的源文件,打包成fileName名称的zip文件,并存放到zipFilePath路径下
    • @param sourceFilePath :待压缩的文件路径
    • @param zipFilePath :压缩后存放路径
    • @param fileName :压缩后文件的名称
    • @return
      */
      public static boolean zipFile(String sourceFilePath, String zipFilePath, String fileName) {
      boolean flag = false;
      File sourceFile = new File(sourceFilePath);
      FileInputStream fis = null;
      BufferedInputStream bis = null;
      FileOutputStream fos = null;
      ZipOutputStream zos = null;
      log.info(“开始压缩文件夹”);
      if (sourceFile.exists() == false) {
      log.error(“待压缩的文件目录:” + sourceFilePath + “不存在”);
      } else {
      try {
      File zipFile = new File(zipFilePath + fileName);
      if (zipFile.exists()) {
      log.warn(“当前压缩的文件已存在”);
      } else {
      File[] sourceFiles = sourceFile.listFiles();
      if (null == sourceFiles || sourceFiles.length < 1) {
      log.error(“待压缩的文件目录:” + sourceFilePath + “里面文件无需压缩”);
      } else {
      fos = new FileOutputStream(zipFile);
      zos = new ZipOutputStream(new BufferedOutputStream(fos));
      byte[] bufs = new byte[1024 * 10];
      for (int i = 0; i < sourceFiles.length; i++) {
      //创建ZIP实体,并添加进压缩包
      ZipEntry zipEntry = new ZipEntry(sourceFiles[i].getName());
      zos.putNextEntry(zipEntry);
      //读取待压缩的文件并写进压缩包里
      fis = new FileInputStream(sourceFiles[i]);
      bis = new BufferedInputStream(fis, 1024 * 10);
      int read = 0;
      while ((read = bis.read(bufs, 0, 1024 * 10)) != -1) {
      zos.write(bufs, 0, read);
      }
      }
      flag = true;
      }
      }
      log.info(“压缩文件夹完成”);
      } catch (FileNotFoundException e) {
      log.error(“压缩文件:{}失败:{}”, fileName, e);
      throw new RuntimeException(e);
      } catch (IOException e) {
      log.error(“压缩文件:{}失败:{}”, fileName, e);
      throw new RuntimeException(e);
      } finally {
      //关闭流
      try {
      if (null != bis) bis.close();
      if (null != zos) zos.close();
      } catch (IOException e) {
      log.error(“压缩文件:{}失败:{}”, fileName, e);
      throw new RuntimeException(e);
      }
      }
      }
      return flag;
      }

    public static boolean deleteDir(File dirFile) {
    // 如果dir对应的文件不存在,则退出
    if (!dirFile.exists()) {
    return false;
    }
    if (dirFile.isFile()) {
    return dirFile.delete();
    } else {
    for (File file : dirFile.listFiles()) {
    deleteDir(file);
    }
    }
    return dirFile.delete();
    }

    public static String getLatestFile(String dir, String taskName) {
    File dirFile = new File(dir);
    if (!dirFile.exists()) {
    return null;
    }
    if (dirFile.isFile()) {
    return null;
    }
    File[] files = dirFile.listFiles();
    if (files.length == 0) return null;
    int k = 0;
    String fileName = “”;
    for (File f : files) {
    String fileNameA = f.getAbsolutePath();
    if (!fileNameA.endsWith(“xls”) && !fileNameA.endsWith(“xlsx”)) continue;
    int pos = fileNameA.indexOf(taskName);
    int pos1 = fileNameA.substring(pos + taskName.length()).indexOf(“.”);
    int a = Integer.valueOf(fileNameA.substring(pos + taskName.length()).substring(0, pos1));
    if (a > k) {
    k = a;
    fileName = fileNameA;
    }
    }
    return fileName;
    }
    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
package com.hexiang.utils; import java.io.*; /** * FileUtil. Simple file operation class. * * @author BeanSoft * */ public class FileUtil { /** * The buffer. */ protected static byte buf[] = new byte[1024]; /** * Read content from local file. FIXME How to judge UTF-8 and GBK, the * correct code should be: FileReader fr = new FileReader(new * InputStreamReader(fileName, "ENCODING")); Might let the user select the * encoding would be a better idea. While reading UTF-8 files, the content * is bad when saved out. * * @param fileName - * local file name to read * @return * @throws Exception */ public static String readFileAsString(String fileName) throws Exception { String content = new String(readFileBinary(fileName)); return content; } /** * 读取文件并返回为给定字符集的字符串. * @param fileName * @param encoding * @return * @throws Exception */ public static String readFileAsString(String fileName, String encoding) throws Exception { String content = new String(readFileBinary(fileName), encoding); return content; } /** * 读取文件并返回为给定字符集的字符串. * @param fileName * @param encoding * @return * @throws Exception */ public static String readFileAsString(InputStream in) throws Exception { String content = new String(readFileBinary(in)); return content; } /** * Read content from local file to binary byte array. * * @param fileName - * local file name to read * @return * @throws Exception */ public static byte[] readFileBinary(String fileName) throws Exception { FileInputStream fin = new FileInputStream(fileName); return readFileBinary(fin); } /** * 从输入流读取数据为二进制字节数组. * @param streamIn * @return * @throws IOException */ public static byte[] readFileBinary(InputStream streamIn) throws IOException { BufferedInputStream in = new BufferedInputStream(streamIn); ByteArrayOutputStream out = new ByteArrayOutputStream(10240); int len; while ((len
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值