rar4,zip壓縮文件,解壓成流的方式在根據要求生成文件
首先maven依賴
<!-- 導入zip解壓包(可以解決中文亂碼) -->
<dependency>
<groupId>ant</groupId>
<artifactId>ant</artifactId>
<version>1.6.5</version>
</dependency>
<!-- 導入rar解壓包 -->
<dependency>
<groupId>com.github.junrar</groupId>
<artifactId>junrar</artifactId>
<version>0.7</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-compress</artifactId>
<version>1.8.1</version>
</dependency>
源碼
package com.example.datasource2;
import com.github.junrar.Archive;
import com.github.junrar.rarfile.FileHeader;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipFile;
import org.codehaus.plexus.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import javax.validation.constraints.NotNull;
import java.io.*;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RarUtils {
public static final String RAR_FILE = ".rar";
public static final String ZIP_FILE = ".zip";
public static String LINUX_SEQ = "/";
public static String WINDOWS_SEQ = "\\\\";
public static Map<String, InputStream> getFileDesc(@NotNull String tempPath,String fileOriName, @NotNull MultipartFile multipartFile, String endCode) throws Exception {
File file = multipartFileToFile(tempPath, multipartFile);
return getFileDesc(file,fileOriName, endCode);
}
public static Map<String, InputStream> getFileDesc(@NotNull File file,String fileOriName, String endCode) throws Exception {
if (StringUtils.isBlank(fileOriName)) {
fileOriName = file.getName();
}
Map<String, InputStream> resultMap;
if (fileOriName.toLowerCase().endsWith(RAR_FILE)) {
resultMap = readRar(file);
} else if (fileOriName.toLowerCase().endsWith(ZIP_FILE)) {
resultMap = readZipFile(file, endCode);
} else {
throw new Exception("暫不支持此壓縮文件!");
}
return resultMap;
}
public static File multipartFileToFile(String tempPath, MultipartFile mf) throws IllegalStateException, IOException {
if (mf == null) {
return null;
}
String name = mf.getName();
File fileTemp = new File(tempPath);
if (!fileTemp.exists()) {
fileTemp.mkdirs();
}
File file = new File(fileTemp + File.separator + name);
mf.transferTo(file);
return file;
}
public static File saveTempFile(MultipartFile multipartFile, String tempDir) throws Exception {
if (multipartFile == null) {
return null;
}
if (tempDir == null || tempDir.trim().length() == 0) {
throw new Exception("臨時路徑不能爲空!");
}
String fileName = multipartFile.getName();
String tempFilePath = tempDir + File.separator + fileName;
File tempFile = new File(tempFilePath);
File parent = tempFile.getParentFile();
if (!parent.exists()) {
parent.mkdir();
}
boolean createResult = tempFile.createNewFile();
if (createResult) {
multipartFile.transferTo(tempFile);
}
multipartFile = null;
return tempFile;
}
public static Map<String, InputStream> readZipFile(File zipFile, String enCoding) throws Exception {
if (zipFile == null) {
throw new Exception("文件爲空!");
}
if (enCoding == null || enCoding.trim().length() == 0) {
enCoding = System.getProperty("file.encoding");
}
ZipFile zf = new ZipFile(zipFile, enCoding);
Map<String, InputStream> fileMap = new HashMap<String, InputStream>(16);
for (Enumeration<ZipEntry> enumeration = zf.getEntries(); enumeration.hasMoreElements(); ) {
ZipEntry zipEntry = enumeration.nextElement();
String name = zipEntry.getName();
name = name.replaceAll(LINUX_SEQ, "※").replaceAll(WINDOWS_SEQ, "※");
if (name.endsWith(WINDOWS_SEQ)) {
continue;
}
InputStream in = zf.getInputStream(zipEntry);
fileMap.put(name, in);
}
return fileMap;
}
public static Map<String, InputStream> readRar(File rarFile) throws Exception {
FileOutputStream outputStream = null;
InputStream in = null;
String fileName = rarFile.getName();
String pathName = null;
Map<String, InputStream> resultMap = new HashMap<>(16);
if (!fileName.toLowerCase().endsWith(RAR_FILE)) {
System.err.println("非rar文件!");
return resultMap;
}
Archive a = new Archive(rarFile);
if (a.getFileHeaders().size() > 0) {
a.getMainHeader().print();
FileHeader fh;
while ((fh = a.nextFileHeader()) != null) {
if (fh.isDirectory()) {
continue;
} else {
if (existZH(fh.getFileNameW())) {
pathName = fileName.substring(0, fileName.lastIndexOf(".")) + File.separator + fh.getFileNameW().trim();
} else {
pathName = fileName.substring(0, fileName.lastIndexOf(".")) + File.separator + fh.getFileNameString().trim();
}
File tempFile = File.createTempFile(System.currentTimeMillis() + "", pathName.substring(pathName.lastIndexOf(".")));
outputStream = new FileOutputStream(tempFile);
a.extractFile(fh, outputStream);
in = new FileInputStream(tempFile);
String replaceName = pathName.replaceAll(WINDOWS_SEQ, "※").replaceAll(LINUX_SEQ, "※");
resultMap.put(replaceName, in);
}
}
a.close();
}
return resultMap;
}
public static boolean existZH(String str) {
String zhStr = "[\\u4e00-\\u9fa5]";
Pattern pattern = Pattern.compile(zhStr);
Matcher matcher = pattern.matcher(str);
if (matcher.find()) {
return true;
}
return false;
}
public static String generateFile(String savePath, String fileName, InputStream inputStream) throws IOException {
FileOutputStream fileOutputStream = null;
try {
String saveName = savePath + File.separator + fileName;
File file = new File(saveName);
fileOutputStream = new FileOutputStream(file);
byte[] buffer = new byte[8 * 1024];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
fileOutputStream.write(buffer, 0, bytesRead);
}
return file.getAbsolutePath();
} catch (IOException e) {
e.printStackTrace();
throw e;
} finally {
if (fileOutputStream != null) {
fileOutputStream.close();
}
if (inputStream != null) {
inputStream.close();
}
}
}
public static void unrar(String rarPath, String dstPath) throws Exception {
if (!rarPath.toLowerCase().endsWith(RAR_FILE)) {
System.err.println("非rar文件");
return;
}
File dstDiretory = new File(dstPath);
if (!dstDiretory.exists()) {
dstDiretory.mkdirs();
}
File fol = null, out = null;
Archive a = null;
try {
a = new Archive(new File(rarPath));
if (a.getFileHeaders().size() > 0) {
a.getMainHeader().print();
FileHeader fh = a.nextFileHeader();
while (fh != null) {
if (fh.isDirectory()) {
if (existZH(fh.getFileNameW())) {
fol = new File(dstPath + File.separator + fh.getFileNameW());
} else {
fol = new File(dstDiretory + File.separator + fh.getFileNameString());
}
fol.mkdirs();
} else {
if (existZH(fh.getFileNameW())) {
out = new File(dstPath + File.separator + fh.getFileNameW().trim());
} else {
out = new File(dstPath + File.separator + fh.getFileNameString().trim());
}
try {
if (!out.exists()) {
if (!out.getParentFile().exists()) {
out.getParentFile().mkdirs();
}
out.createNewFile();
}
FileOutputStream os = new FileOutputStream(out);
a.extractFile(fh, os);
} catch (Exception ex) {
ex.printStackTrace();
}
}
fh = a.nextFileHeader();
}
a.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}