zip、rar格式文件解压缩处理
文章目录
- zip、rar格式文件解压缩处理
- 核心pom依赖引入
- 核心工具类FileUtil.java
- 统一接口
- rar格式解压缩处理
- zip格式解压缩处理
zip、rar格式文件解压缩处理
在相关业务场景中,批量文件处理,需要预先进行解压缩及拷贝处理
核心pom依赖引入
<!-- 导入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>4.0.0</version>
</dependency>
<dependency>
<groupId>com.github.jnr</groupId>
<artifactId>jnr-posix</artifactId>
<version>3.0.50</version>
</dependency>
核心工具类FileUtil.java
public static boolean unPackagedFile(String filename,String dir){
InfDecompress rarDecompress = null;
if(filename.endsWith(".rar")){
rarDecompress = new RarDecompress(); //需要用rar4格式的压缩包能被解析,高版本不行
}else if(filename.endsWith(".zip")){
rarDecompress = new ZipDecompress();
}else{
logger.error("不支持的解包扩展名格式");
return false;
}
if(!rarDecompress.decompressFile(filename,dir)){
logger.error(filename + "解压失败");
return false;
}
return true;
}
public static int copyFilesOfDir(String srcDirPath, String desDirPath) {
if (!srcDirPath.endsWith(File.separator)) {
srcDirPath = srcDirPath + File.separator;
}
if (!desDirPath.endsWith(File.separator)) {
desDirPath = desDirPath + File.separator;
}
File srcfile = new File(srcDirPath);
if (srcfile.exists()) {
String[] fileNames = srcfile.list();
//及时是个空目录 也要创建一个空的目标目录
if (fileNames != null) {
if (!new File(desDirPath).exists()) {
if (!new File(desDirPath).mkdirs()) {
logger.error("{failed to mkdirs " + desDirPath + "}");
return -1;
}
}
}
else {
return -1;
}
for (String fileName : fileNames) {
File fileToCopy = null;
if (srcDirPath.endsWith(File.separator)) {
fileToCopy = new File(srcDirPath + fileName);
} else {
fileToCopy = new File(srcDirPath + File.separator + fileName);
}
if (fileToCopy.isFile()) {
//copy file
FileInputStream inputStream = null;
FileOutputStream outputStream = null;
try {
inputStream = new FileInputStream(fileToCopy);
if (desDirPath.endsWith(File.separator)) {
outputStream = new FileOutputStream(desDirPath + fileToCopy.getName());
} else {
outputStream = new FileOutputStream(desDirPath + File.separator + fileToCopy.getName());
}
byte[] buffer = new byte[10240];
int len;
while ((len = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, len);
}
outputStream.flush();
outputStream.close();
inputStream.close();
} catch (FileNotFoundException ex) {
logger.error(ex.getMessage());
return -1;
} catch (IOException ex) {
logger.error(ex.getMessage());
return -1;
} finally {
}
} else {
continue;
}
}
}
return 0;
}
public static int copyFile(String srcFileNm,String DesFileNm)
{
InputStream input = null;
OutputStream output = null;
try{
File inFile = new File(srcFileNm);
File outFile = new File(DesFileNm);
/*if(!outFile.exists())
outFile.createNewFile();*/
input = new FileInputStream(inFile);
output = new FileOutputStream(outFile);
byte[] buf = new byte[1024];
int bytesRead;
while ((bytesRead = input.read(buf)) > 0) {
output.write(buf, 0, bytesRead);
}
}catch (Exception e){
logger.error("copyFileToDstdir 文件拷贝失败,src:" + srcFileNm + " dst:" + DesFileNm + "errorMsg:" + e.getLocalizedMessage());
return -1;
}finally {
try{
if(input != null){
input.close();
}
if(output != null){
output.close();
}
}catch (IOException e){
logger.error(e.getMessage());
}
}
return 0;
}
public static int deleteDirRecursively(String absoluteDirPath)
{
File dir=new File(absoluteDirPath);
if(!dir.isDirectory())
{
if(!dir.delete())
{
logger.error("delete file failed "+ dir.getAbsolutePath());
return -1;
}
return 0;
}
else
{
String[] fileList=dir.list();
for(String fileName:fileList)
{
String absolutePath=absoluteDirPath+File.separator+fileName;
if(deleteDirRecursively(absolutePath)<0)
{
logger.error("delete file failed "+absolutePath);
return -1;
}
}
if(fileList.length==0)
{
if(!dir.delete())
{
logger.error(dir.getAbsolutePath()+" delele failed");
return -1;
}
}
}
return 0;
}
/**
* 从fileName全路径中,获取文件名称
* @param fileName
* @return
*/
public static String getIndexOfFile(String fileName){
if(fileName == null){
return fileName;
}
if(fileName.lastIndexOf("\\") != -1){
return fileName.substring(fileName.lastIndexOf("\\")+1);
}
if(fileName.lastIndexOf("/") != -1){
return fileName.substring(fileName.lastIndexOf("/")+1);
}
return fileName;
}
统一接口
public interface InfDecompress {
boolean decompressFile(String fn,String dest);
}
rar格式解压缩处理
import com.github.junrar.Archive;
import com.github.junrar.rarfile.FileHeader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
public class RarDecompress implements InfDecompress{
private static Logger logger = LoggerFactory.getLogger(RarDecompress.class);
@Override
public boolean decompressFile(String fn,String dest) {
Archive a = null;
try {
File inFile = new File(fn);
a = new Archive(new FileInputStream(inFile));
if(a!=null){
FileHeader fh = a.nextFileHeader();
while(fh != null){
if(fh.isDirectory()){
File fol = new File(dest + File.separator + fh.getFileNameString());
fol.mkdirs();
}else{
String unpackFile = dest + File.separator + fh.getFileNameString().trim();
File out = new File(unpackFile);
if(!out.exists()){
if (!out.getParentFile().exists()) {// 相对路径可能多级,可能需要创建父目录.
out.getParentFile().mkdirs();
}
out.createNewFile();
}
FileOutputStream os = new FileOutputStream(out);
a.extractFile(fh, os);
os.close();
if(unpackFile.endsWith(".rar") || unpackFile.endsWith(".zip")){ //子文件下还有被压缩的文件
UnPackage.unPackagedFile(unpackFile,unpackFile.substring(0,unpackFile.lastIndexOf(File.separator)));
}
}
fh = a.nextFileHeader();
}
}else {
logger.error("Rar decompressFile异常");
return false;
}
a.close();
return true;
}catch (Exception e){
logger.error("解压" + fn + "文件失败" + e.getLocalizedMessage());
}
return false;
}
}
zip格式解压缩处理
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipFile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
public class ZipDecompress implements InfDecompress{
private static Logger logger = LoggerFactory.getLogger(ZipDecompress.class);
@Override
public boolean decompressFile(String fn,String dest) {
try {
ZipFile zip = new ZipFile(fn,"gbk");
for (Enumeration entries = zip.getEntries(); entries.hasMoreElements(); ) {
ZipEntry entry = (ZipEntry) entries.nextElement();
String zipEntryName = entry.getName();
String unpackFile = dest + File.separator + zipEntryName.trim();
InputStream in = zip.getInputStream(entry);
OutputStream out = new FileOutputStream(dest + File.separator + zipEntryName);
if (new File(zipEntryName).isDirectory()) {
continue;
}
byte[] buf1 = new byte[1024];
int len;
while ((len = in.read(buf1)) > 0) {
out.write(buf1, 0, len);
}
in.close();
out.close();
if(unpackFile.endsWith(".rar") || unpackFile.endsWith(".zip")){ //子文件下还有被压缩的文件
UnPackage.unPackagedFile(unpackFile,unpackFile.substring(0,unpackFile.lastIndexOf(File.separator)));
}
}
zip.close();
}catch (Exception e){
logger.error("Zip decompressFile异常");
return false;
}
return true;
}
}
学习Java的同学注意了!!!
学习过程中遇到什么问题或者想获取学习资源的话,欢迎加入Java学习交流群,群号码:543120397 我们一起学Java!
还没有评论,来说两句吧...