java文件操作方法封装

创建临时文件

  • // 临时文件夹路径
    String directoryPath = System.getProperty("java.io.tmpdir");
    /**
     * 创建文件
     */
    private void createFile(String fileName, String directoryPath, byte[] result) {
        // 创建文件目录
        String filePath = directoryPath + fileName + "/";
        File directory = new File(filePath);
        if (!directory.exists()) {
            directory.mkdirs();
        }
        // byte数组转file
        byte2File(result, filePath, fileName + ".jpg");
        log.info("创建临时文件成功");
    }
    

byte和file互转

  • /**
     * byte转file
     */
    public File byte2File(byte[] buf, String filePath, String fileName) {
      BufferedOutputStream bos = null;
      FileOutputStream fos = null;
      File file = null;
      try {
          String path = StringUtils.isEmpty(filePath)? "" : filePath;
          File dir = new File(path);
          if (!dir.exists() && dir.isDirectory()) {
              dir.mkdirs();
          }
          file = new File(filePath + File.separator + fileName);
          fos = new FileOutputStream(file);
          bos = new BufferedOutputStream(fos);
          bos.write(buf);
      } catch (Exception e) {
          e.printStackTrace();
      } finally {
          if (bos != null) {
              try {
                  bos.close();
              } catch (IOException e) {
                  e.printStackTrace();
              }
          }
          if (fos != null) {
              try {
                  fos.close();
              } catch (IOException e) {
                  e.printStackTrace();
              }
          }
      }
      return file;
    }
    
    /**
     * file转byte
     */
    public static byte[] file2byte(File file) {
      byte[] buffer = null;
      try (FileInputStream fis = new FileInputStream(file);
            ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
          byte[] b = new byte[1024];
          int n;
          while ((n = fis.read(b)) != -1) {
              bos.write(b, 0, n);
          }
          buffer = bos.toByteArray();
      } catch (FileNotFoundException e) {
          e.printStackTrace();
      } catch (IOException e) {
          e.printStackTrace();
      }
      return buffer;
    }
    

打包ZIP

  • /**
     * 打包ZIP
     */
    private void packageToZip(String directoryPath, String zipFilePath) {
        // 创建一个输出流将数据写入ZIP文件
        try (FileOutputStream fos = new FileOutputStream(zipFilePath);
             ZipOutputStream zos = new ZipOutputStream(fos)) {
            // 调用递归方法压缩文件或文件夹
            addToZipFile(directoryPath, directoryPath, zos);
            log.info("文件已成功打包成 " + zipFilePath);
        } catch (IOException e) {
            log.error("文件打包异常");
        }
    }
    private void addToZipFile(String path, String sourceFile, ZipOutputStream zos) throws IOException {
        File file = new File(sourceFile);
        // 如果是文件夹,则获取其内容并递归调用此方法
        if (file.isDirectory()) {
            String[] fileList = file.list();
            if (fileList != null) {
                for (String fileName : fileList) {
                    addToZipFile(path, sourceFile + File.separator + fileName, zos);
                }
            }
            return;
        }
        // 如果是文件,则将其添加到ZIP文件中
        try (FileInputStream fis = new FileInputStream(sourceFile)) {
            String entryName = sourceFile.substring(path.length() + 1); // 获取ZIP中的条目名称
            ZipEntry zipEntry = new ZipEntry(entryName);
            zos.putNextEntry(zipEntry);
            byte[] bytes = new byte[1024];
            int length;
            while ((length = fis.read(bytes)) >= 0) {
                zos.write(bytes, 0, length);
            }
        }
    }
    
    

下载zip文件

  • /**
     * 下载ZIP
     */
    private void downloadZip(HttpServletResponse response, String zipFilePath) {
      // 设置响应头,告诉浏览器这是一个文件下载
      response.setContentType("application/zip");
      response.setHeader("Content-Disposition", "attachment; filename=qrCodes.zip");
      // 读取zip文件并写入响应输出流
      File zipFile = new File(zipFilePath);
      try (FileInputStream fis = new FileInputStream(zipFile);
           OutputStream os = response.getOutputStream()) {
          byte[] buffer = new byte[1024];
          int len;
          while ((len = fis.read(buffer)) != -1) {
              os.write(buffer, 0, len);
          }
      } catch (IOException e) {
          log.error("文件下载异常");
      }
    }
    

删除临时文件

  • /**
     * 删除文件
     */
    private void removeTempFile(String directoryPath, String zipFilePath) {
      // 删除zip文件
      deleteFolder(new File(zipFilePath));
      // 递归删除文件夹
      deleteFolder(new File(directoryPath));
      log.info("删除临时文件成功");
    }
    private void deleteFolder(File folder) {
      if (folder.isDirectory()) {
          File[] files = folder.listFiles();
          if (files != null) {
              for (File file : files) {
                  deleteFolder(file);
              }
          }
      }
      folder.delete();
    }
    
  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

fearIess233

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值