java8正确处理文件Files

1. 逐行读取文件

需要使用 try-with-resources 语句来保证stream的close方法被调用,从而关闭打开的文件

// try-with-resources语句,等同于try-catch-finally
try(Stream<String> stream = Files.lines(Paths.get(filePath))){
	stream.collect(Collectors.toList());
} catch (IOException e){
    logger.error("get content from{} error,{}",filePath, e);
}

2. 解压文件

  /**
   * 解压文件后删除
   *
   * @param zipPath 解压文件路径,例如D:\aaaaa\I_20210101_zxgg.zip
   */
  public void unzipThenRemove(String zipPath) {
    String savePath = Constant.FAHAI_SFTP_DOWNLOAD_LOCAL_PATH;
    try (ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(zipPath)); ) {
      ZipEntry zipEntry;
      while ((zipEntry = zipInputStream.getNextEntry()) != null && !zipEntry.isDirectory()) {
        File unzipFile = new File(savePath + File.separator + zipEntry.getName());
        OutputStream outputStream = new FileOutputStream(unzipFile);
        IOUtil.copy(outputStream, zipInputStream);
        outputStream.close();
        logger.info("{} 压缩包解压 : {}", zipPath, unzipFile.getAbsoluteFile());
      }
      zipInputStream.closeEntry();
      Files.deleteIfExists(Paths.get(zipPath));
    } catch (IOException e) {
      logger.error("文件解压删除失败 : {}", zipPath, e);
    }
  }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

ZHAIKEsir

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

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

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

打赏作者

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

抵扣说明:

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

余额充值