java unzip类_Java 原生API 实现zip和unzip (用文件和响应流两种方式)

本文介绍了一个Java工具类`HandleZipFile`,用于使用Java原生API进行zip和unzip操作,包括从文件和HTTP响应流中解压。类中提供了压缩文件和目录,以及从输入流解压文件的方法。
摘要由CSDN通过智能技术生成

package com.ford.dsl.controller;

import org.springframework.http.HttpEntity;

import org.springframework.http.HttpMethod;

import org.springframework.web.client.RestTemplate;

import java.io.*;

import java.util.ArrayList;

import java.util.List;

import java.util.zip.ZipEntry;

import java.util.zip.ZipInputStream;

import java.util.zip.ZipOutputStream;

/**

* Zip压缩/解压缩工具类

* 实现对目标路径及其子路径下的所有文件及空目录的压缩

* 参考网上若干种实现,并修改其bug

*

* @version v0.1, 17/09/04

* @author Kiwi Liu

*/

public class HandleZipFile {

/** 缓冲器大小 */

private static final int BUFFER = 512;

/**

* 取的给定源目录下的所有文件及空的子目录

* 递归实现

*

* @param srcFile

*

* @return

*/

private static List getAllFiles(File srcFile) {

List fileList = new ArrayList();

File[] tmp = srcFile.listFiles();

for (int i = 0; i < tmp.length; i++) {

if (tmp[i].isFile()) {

fileList.add(tmp[i]);

System.out.println("add file: "+tmp[i].getName());

}

if (tmp[i].isDirectory()) {

if (tmp[i].listFiles().length!=0){//若不是空目录,则递归添加其下的目录和文件

fileList.addAll(getAllFiles(tmp[i]));

}

else{//若是空目录,则添加这个目录到fileList

fileList.add(tmp[i]);

System.out.println("add empty dir: "+tmp[i].getName());

}

}

} // end for

return fileList;

}

/**

* 取相对路径

* 依据文件名和压缩源路径得到文件在压缩源路径下的相对路径

*

* @param dirPath 压缩源路径

* @param file

*

* @return 相对路径

*/

private static String getRelativePath(String dirPath, File file) {

File dir = new File(dirPath);

String relativePath = file.getName();

while (true) {

file = file.getParentFile();

if (file == null) {

break;

}

if (file.equals(dir)) {

break;

} else {

relativePath = file.getName() + "/" + relativePath;

}

} // end while

return relativePath;

}

/**

* 创建文件

* 根据压缩包内文件名和解压缩目的路径,创建解压缩目标文件,

* 生成中间目录

* @param dstPath 解压缩目的路径

* @param fileName 压缩包内文件名

*

* @return 解压缩目标文件

*

* @throws IOException

*/

private static File createFile(String dstPath, String fileName) throws IOException {

String[] dirs = fileName.split("/");//将文件名的各级目录分解

File file = new File(dstPath);

if (dirs.length > 1) {//文件有上级目录

for (int i = 0; i < dirs.length - 1; i++) {

file = new File(file, dirs[i]);//依次创建文件对象知道文件的上一级目录

}

if (!file.exists()) {

file.mkdirs();//文件对应目录若不存在,则创建

System.out.println("mkdirs: " + file.getCanonicalPath());

}

file = new File(file, dirs[dirs.length - 1]);//创建文件

return file;

} else {

if (!file.exists()) {

file.mkdirs();//若目标路径的目录不存在,则创建

System.out.println("mkdirs: " + file.getCanonicalPath());

}

file = new File(file, dirs[0]);//创建文件

return file;

}

}

/**

* 解压缩方法

*

*

* @param zipFileName 压缩文件名

* @param dstPath 解压目标路径

*

* @return

*/

public static boolean unzip(String zipFileName, String dstPath) {

System.out.println("zip uncompressing...");

try {

ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(zipFileName));

ZipEntry zipEntry = null;

byte[] buffer = new byte[BUFFER];//缓冲器

int readLength = 0;//每次读出来的长度

while ((zipEntry = zipInputStream.getNextEntry()) != null) {

if (zipEntry.isDirectory()) {//若是zip条目目录,则需创建这个目录

File dir = new File(dstPath + "/" + zipEntry.getName());

if (!dir.exists()) {

dir.mkdirs();

System.out.println("mkdirs: " + dir.getCanonicalPath());

continue;//跳出

}

}

File file = createFile(dstPath, zipEntry.getName());//若是文件,则需创建该文件

System.out.println("file created: " + file.getCanonicalPath());

OutputStream outputStream = new FileOutputStream(file);

while ((readLength = zipInputStream.read(buffer, 0, BUFFER)) != -1) {

outputStream.write(buffer, 0, readLength);

}

outputStream.close();

System.out.println("file uncompressed: " + file.getCanonicalPath());

} // end while

} catch (FileNotFoundException e) {

System.out.println(e.getMessage());

e.printStackTrace();

System.out.println("unzip fail!");

return false;

} catch (IOException e) {

System.out.println(e.getMessage());

e.printStackTrace();

System.out.println("unzip fail!");

return false;

}

System.out.println("unzip success!");

return true;

}

/**

* 压缩方法

* (可以压缩空的子目录)

* @param srcPath 压缩源路径

* @param zipFileName 目标压缩文件

*

* @return

*/

public static boolean zip(String srcPath, String zipFileName) {

System.out.println("zip compressing...");

File srcFile = new File(srcPath);

List fileList = getAllFiles(srcFile);//所有要压缩的文件

byte[] buffer = new byte[BUFFER];//缓冲器

ZipEntry zipEntry = null;

int readLength = 0;//每次读出来的长度

try {

ZipOutputStream zipOutputStream = new ZipOutputStream(new FileOutputStream(zipFileName));

for (File file : fileList) {

if (file.isFile()){//若是文件,则压缩这个文件

zipEntry = new ZipEntry(getRelativePath(srcPath, file));

zipEntry.setSize(file.length());

zipEntry.setTime(file.lastModified());

zipOutputStream.putNextEntry(zipEntry);

InputStream inputStream = new BufferedInputStream(new FileInputStream(file));

while ((readLength = inputStream.read(buffer, 0, BUFFER)) != -1) {

zipOutputStream.write(buffer, 0, readLength);

}

inputStream.close();

System.out.println("file compressed: " + file.getCanonicalPath());

}else {//若是目录(即空目录)则将这个目录写入zip条目

zipEntry = new ZipEntry(getRelativePath(srcPath, file)+"/");

zipOutputStream.putNextEntry(zipEntry);

System.out.println("dir compressed: " + file.getCanonicalPath()+"/");

}

} // end for

zipOutputStream.close();

} catch (FileNotFoundException e) {

System.out.println(e.getMessage());

e.printStackTrace();

System.out.println("zip fail!");

return false;

} catch (IOException e) {

System.out.println(e.getMessage());

e.printStackTrace();

System.out.println("zip fail!");

return false;

}

System.out.println("zip success!");

return true;

}

public static void main(String[] args) {

//unzip2("F:\\FordCRDocument\\China PCF\\UserVehicle\\image\\THEN-colourcsv.csv.zip", "F:\\FordCRDocument\\China PCF\\UserVehicle\\image\\");

String url = "https://wwwxxxx.xxx.com";

RestTemplate restTemplate = new RestTemplate();

HttpEntity entity = restTemplate.exchange(url, HttpMethod.GET, null, byte[].class);

ByteArrayInputStream inputStream = new ByteArrayInputStream(entity.getBody());

unzipByInputStream(inputStream);

}

public static boolean unzipByInputStream(InputStream inputStream) {

System.out.println("zip uncompressing...");

try {

ZipInputStream zipInputStream = new ZipInputStream(inputStream);

ZipEntry zipEntry = null;

byte[] buffer = new byte[BUFFER];//缓冲器

int readLength = 0;//每次读出来的长度

while ((zipEntry = zipInputStream.getNextEntry()) != null) {

if (zipEntry.isDirectory()) {//若是zip条目目录,则需创建这个目录

/*File dir = new File(dstPath + "/" + zipEntry.getName());

if (!dir.exists()) {

dir.mkdirs();

System.out.println("mkdirs: " + dir.getCanonicalPath());

continue;//跳出

}*/

System.out.println("zipfile is a directory: " + zipEntry.getName());

System.out.println("Pass");

}

//File file = createFile(dstPath, zipEntry.getName());//若是文件,则需创建该文件

System.out.println("zipfile is a file: " + zipEntry.getName());

ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

while ((readLength = zipInputStream.read(buffer, 0, BUFFER)) != -1) {

outputStream.write(buffer, 0, readLength);

}

byte[] arrs = outputStream.toByteArray();

String str = new String(arrs, "UTF-8");

System.out.println(str);

outputStream.close();

} // end while

} catch (FileNotFoundException e) {

System.out.println(e.getMessage());

e.printStackTrace();

System.out.println("unzip fail!");

return false;

} catch (IOException e) {

System.out.println(e.getMessage());

e.printStackTrace();

System.out.println("unzip fail!");

return false;

}

System.out.println("unzip success!");

return true;

}

}

//~ Formatted by Jindent --- http://www.jindent.com

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值