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);
}
}