1、依赖引入
<!-- io -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
<!-- 谷歌guava文件操作 -->
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>18.0</version>
</dependency>
<!-- 压缩文件操作 -->
<dependency>
<groupId>net.lingala.zip4j</groupId>
<artifactId>zip4j</artifactId>
<version>1.3.3</version>
</dependency>
2、相关操作代码
package com.poi.testpoi.util;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.poi.testpoi.service.Impl.HandleProvinceOutDataServiceImpl;
import net.lingala.zip4j.core.ZipFile;
import net.lingala.zip4j.model.ZipParameters;
import net.lingala.zip4j.util.Zip4jConstants;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.List;
import java.util.stream.Collectors;
public class FileUtils {
private static org.slf4j.Logger logger = LoggerFactory.getLogger(HandleProvinceOutDataServiceImpl.class);
public static void deleteFile(String filename) {
File file = new File(filename);
file.deleteOnExit();
}
public static void appendListFile(String filename, List<?> content) {
List<String> filtered = content.stream().map(obj -> JSON.toJSONString(obj, SerializerFeature.WriteDateUseDateFormat, SerializerFeature.WriteNullStringAsEmpty)).collect(Collectors.toList());
appendFile(filename, filtered);
}
public static synchronized void appendFile(String filename, List<String> content)
{
File file = new File(System.getProperty("user.home")+filename);
try
{
if (!file.exists())
{
String parent = file.getParent();//返回此抽象路径的父目录的路径字符串
Path parentPath = Paths.get(parent);//将路径字符串转换为路径
Files.createDirectories(parentPath);//根据路径创建目录
com.google.common.io.Files.touch(file);//touch方法创建或者更新文件的时间戳。
}
Path path = Paths.get(file.toURI());//根据文件路径得到URI
Files.write(path, content, Charset.forName("UTF-8"), StandardOpenOption.APPEND);//StandardOpenOption.APPEND 表示以追加的形式将内容写入文件
//将数据进行加密并压缩
// String zipFilePath = filename.replace(".cvs", ".zip");
// encryZipFile(new File(zipFilePath), file, "123456");
} catch (IOException e)
{
logger.error("文件写入失败", e);
}
}
public static boolean createDirectories(String paths) {
boolean result = true;
Path from = Paths.get(paths);
try {
Files.createDirectories(from);
} catch (IOException e) {
logger.error("文件目录创建失败", e);
result = false;
}
return result;
}
/**
* 对压缩文件进行加密
* @param zipFile 压缩包名称
* @param addFile 需要添加到压缩包的文件
* @param password 加密的密码
*/
public static void encryZipFile(File zipFile, File addFile, String password)
{
ZipFile zipFileDest = null;
try
{
logger.info("开始压缩文件需要参数:{},{},{}", zipFile, addFile.getName(), password);
//创建压缩文件
zipFileDest = new ZipFile(zipFile);
//设置压缩文件参数
ZipParameters parameters = new ZipParameters();
//设置压缩方法
parameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE);
//设置压缩文件加密
parameters.setEncryptFiles(true);
//设置加密方法
parameters.setEncryptionMethod(Zip4jConstants.ENC_METHOD_AES);
//设置aes加密强度
parameters.setAesKeyStrength(Zip4jConstants.AES_STRENGTH_256);
//设置密码
parameters.setPassword(password);
//添加文件到压缩文件
zipFileDest.addFile(addFile,parameters);
} catch (Exception e)
{
logger.error("对压缩文件进行加密失败:{}", e);
}
}
/**
* 对压缩文件进行解压
* @param zipFile
* @param dest
* @param password
*/
public static void upZip(File zipFile,String dest,String password) {
try {
ZipFile zFile = new ZipFile(zipFile);//指向压缩文件.zip
//设置文件名编码,在gbk系统中需要设置,文件名称是中文就不会乱码
// zFile.setFileNameCharset("gbk");
if(!zFile.isValidZipFile()) {// 检查文件是否合法
throw new Exception("文件名不合法");
}
File destFile = new File(dest);//解压目录
if(destFile.isDirectory()&&!destFile.exists()) {
destFile.mkdirs();
}
if(zFile.isEncrypted()) {//如果设置了密码
zFile.setPassword(password.toCharArray());
}
zFile.extractAll(dest);//将文件输出到目标目录
} catch (Exception e) {
e.printStackTrace();
}
}
}