1.压缩zip文件
import java.io.*;
import org.apache.tools.zip.ZipOutputStream;
import org.apache.tools.zip.ZipEntry;
import org.springframework.core.io.FileSystemResource;
/**
* 压缩zip文件
*
* @param List<Attachments> list
* @return
* @throws IOException
*/
public String zipFile(List<Attachments> list) throws IOException {
//默认文件存放地址
String rootPath = "D:\\";
String path = rootPath +"ZIP"+"test.zip";
//遍历获取表中文件路径
List<String> filePath = list.stream().map(e->e.getPath()).collect(Collectors.toList());
//创建zip文件
File file = new File(path);
//判断文件父目录是否存在
if(!file.getParentFile().exists()){
//父目录不存在则创建对应的父目录
file.getParentFile().mkdirs();
}
//读取文件
FileOutputStream inputStream = new FileOutputStream(path);
//输出流
ZipOutputStream out = new ZipOutputStream(inputStream);
//批量获取需要下载的文件
for(int i=0;i<filePath.size();i++){
File downloadFile = new File(rootPath+filePath.get(i));
//判断需要下载的文件是否存在
if(!downloadFile.exists()){
//创建父目录
downloadFile.getParentFile().mkdirs();
//创建新文件
downloadFile.createNewFile();
}
//设置输出流字符编码
out.setEncoding("UTF-8");
//获取数据库中文件的路径和文件名,放入zip文件
FileInputStream inStream = new FileInputStream(downloadFile);
//获取文件名,创建条目并添加到zip中
out.putNextEntry(
new ZipEntry(filePath.get(i).substring(filePath.get(i).lastIndexOf("/")+1))
);
int len;
byte[] buffer = new byte[1024];
//读入需要下载的文件的内容,打包到zip文件
//read(byte[] b) 从输入流中读取一定数量的字节,并将其存储在缓冲区数组 buffer 中。以整数形式返回实际读取的字节数
while ((len = inStream.read(buffer)) > 0) {
out.write(buffer, 0, len);
}
out.closeEntry();
inStream.close();
}
out.close();
return path;
}
2.restTemplate上传zip文件
/**
* 调用三方接口,上传zip文件
* @param token 携带token
* @param url
* @return
*/
public Integer uploadZipFile(String token,String url){
//查询所有数据
List<Attachments> attachments = attachmentsServer.list();
//通过传入的数据压缩成zip文件,返回zip文件存放路径
String zipPath = zipFile(attachments);
//使用系统文件路径方式加载文件
FileSystemResource file = new FileSystemResource(zipPath);
//初始化MultiValueMap,用于封装传递参数
MultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
map.add("file",file);
HttpHeaders headers = new HttpHeaders();
//传递请求携带的token
headers.set(HttpHeaders.AUTHORIZATION, token);
MediaType type = MediaType.MULTIPART_FORM_DATA;
// 设置请求的格式类型
headers.setContentType(type);
HttpEntity<MultiValueMap<String, Object>> entity = new HttpEntity<>(map, headers);
//调用第三方接口,传递zip文件
//url接口请求路径:"http://"+IP地址+":"+端口号
ResponseEntity<Integer> responseEntity = restTemplate.postForEntity(url + "/getzipFile", entity, Integer.class);
//获取statusCode
HttpStatus statusCode = responseEntity.getStatusCode();
if(statusCode.value()==HttpStatus.OK.value() && (null!=responseEntity&&responseEntity.hasBody())){
Integer returnBody = responseEntity.getBody();
System.out.println(returnBody+"===========================");
return returnBody;
}else{
System.out.println("另个系统解析问题!");
// logger.error("与xx系统进行交互时报错,命令:{},请求参数:{}",cmd,JSON.toJSONString(reqBody));
// return getErrorBean(tClass, "与xx系统进行交互时报错:"+cmd);
}
return 0;
}
3.接收zip文件
@ApiOperation(value = "接收zip文件")
@PostMapping("/getzipFile")
public String getzipFile(@RequestPart("file") MultipartFile file, @RequestPart("attachments")List<Attachments> attachments) throws Exception {
//获取文件输入流
InputStream inputStream = file.getInputStream();
//接收zip文件存放路径
String rootPath= "D:"+File.separator+"ZIP1"+File.separator+"test.zip";
//判断文件是否存在
if(!new File(rootPath).exists()){
new File(rootPath).mkdirs();
}
FileOutputStream out = new FileOutputStream(rootPath+"test.zip");
byte[] buffer = new byte[1024];
int len;
//读入需要下载的文件的内容,打包到zip文件
while ((len = inputStream.read(buffer)) > 0 ){
out.write(buffer,0,len);
}
inputStream.close();
out.close();
//另一种把文件上传到指定的文件路径方式
//
//FileUtils.copyInputStreamToFile(file.getInputStream(),new File(rootPath));
//判断需要读取的文件路径列表是否为空,防止空指针异常
if(CollectionUtils.isNotEmpty(attachments)){
//遍历获取数据库存放文件路径
List<String> wjName = attachments.stream().map(e->e.getPath()).collect(Collectors.toList());
//解压zip文件
return zipUncompress(rootPath+"\\sysAttachment.zip",wjName);
}
return "0";
}
4.解压zip文件方法
/**
* 解压zip文件
* @param inputFile zip文件(包括文件存放路径)
* @param wjPath 解压后文件存放路径
* @return
* @throws Exception
*/
public String zipUncompress(String inputFile, List<String> wjPath) throws Exception {
//获取当前压缩文件
File srcFile = new File(inputFile);
// 判断源文件是否存在
if (!srcFile.exists()) {
throw new Exception(srcFile.getPath() + "所指文件不存在");
}
//读取文件名称
List<String> name = wjPath.stream().map(e->e.substring(e.lastIndexOf("/")+1)).collect(Collectors.toList());
//开始解压
//构建解压输入流
ZipInputStream zIn = new ZipInputStream(new FileInputStream(srcFile));
java.util.zip.ZipEntry entry = null;
File file = null;
while ((entry = zIn.getNextEntry()) != null) {
if(!entry.isDirectory()){
if(name.contains(entry.getName())){
String rootPath= MyConfig.getProfile();
file = new File(rootPath+wjPath.get(name.indexOf(entry.getName())));
if (!file.exists()) {
//创建此文件的上级目录
new File(file.getParent()).mkdirs();
}
OutputStream out = new FileOutputStream(file);
BufferedOutputStream bos = new BufferedOutputStream(out);
int len = -1;
byte[] buf = new byte[1024];
while ((len = zIn.read(buf)) != -1) {
bos.write(buf, 0, len);
}
// 关流顺序,先打开的后关闭
bos.close();
out.close();
}
}
}
return "1";
}