【java】文件解压

通过接口接收了一个MultipartFile类型的压缩文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
//临时目录,用于存放shp上传的文件  
@Value("${tempPath}")
protected String tempPath;

//编码格式
@Value("${charset}")
protected String charset;

public String unZipFileToTempPath(MultipartFile upFile) {
String returnPath = null;
String fileName = upFile.getOriginalFilename();
//无后缀文件名
String prefix = fileName.substring(0, fileName.lastIndexOf("."));
// TODO 支持更多种类的压缩文件
if (!fileName.toLowerCase().endsWith(".zip")) {
throw new MyException("仅支持zip压缩文件");
}
OutputStream out = null;
InputStream in = null;
ZipInputStream zipInputStream = null;
try {
//multipartFile转化为file
File file = new File(tempPath + "/" + fileName);
if (!file.getParentFile().exists()) {
//父级目录不存在则创建
file.getParentFile().mkdirs();
log.info("the tempFile Path Is there : {}", file.getAbsolutePath());
}
upFile.transferTo(file);
//创建zip实例化对象
ZipFile zipFile = new ZipFile(file, Charset.forName(charset));
zipInputStream = new ZipInputStream(new FileInputStream(file));
ZipEntry entry;
//临时路径文件夹
File tempFile = new File(tempPath + "/" + prefix + "/");
if (!tempFile.exists()) {
tempFile.mkdirs();
}
while (((entry=zipInputStream.getNextEntry())!=null)&& !entry.isDirectory()) {
//压缩文件内的文件
String entryName = entry.getName();
if (entryName.toLowerCase().endsWith(".shp")) {
//shp完整路径返回
returnPath = tempPath + "/" + prefix + "/" + entryName;
}
out = new FileOutputStream(tempPath + "/" + prefix + "/" + entryName);
//读取压缩文件内文件
in = zipFile.getInputStream(entry);
byte[] buf1 = new byte[1024];
int len;
//写入预定义的临时文件夹内
while((len=in.read(buf1))>0)
{
out.write(buf1,0,len);
}
in.close();
out.close();
}
zipInputStream.close();
zipFile.close();
if (file.exists()) {
//压缩文件解压后删除
if (file.delete()) {
log.info("压缩文件{}清理成功", fileName);
}
}
} catch (Exception e) {
throw new MyException("解压缩文件时出现异常", e);
}
return returnPath;
}

关键配置:

1
2
3
4
5
6
7
8
9
10
11
12
13
spring:
servlet:
multipart:
max-file-size: 100MB #单个文件大小限制
max-request-size: 100MB #单次请求大小限制
enabled: true
# windows
#location: 'C://shpTemp'
# linux
location: '/local/shpPath'
charset: GBK
tempPath: '/local/shpPath' #windows、linux 路径区分
#tempPath: 'C://shpTemp' #windows

spring.servlet.multipart.location配置比较重要,在MultipartFile.transferTo(file)这步操作中,如果判断file的路径是相对路径(实际测试情况很多时候就算用的绝对路径也不知道怎么就识别成了相对路径),就会用一个默认的虚拟路径(很长,不好找),容易找不到文件,报FileNotFoundException。需要设置默认的location,方便文件查找。