当前位置:首页 » 文件管理 » java压缩zip

java压缩zip

发布时间: 2022-10-10 16:13:22

1. java解压zip文件

不好意思搞反了,这样就更简单了。
用这个构造方法ZipInputStream(InputStream in);接收传过来的流,然后用这个类的getNextEntry()方法解压缩文件,最后调用read(byte[] b, int off, int len)方法将数据写入byte数组。
ZipInputStream zin = new ZipInputStream(in);
ZipEntry entry = null;
while((entry=zin.getNextEntry())!=null){
if(entry.isDirectory()||entry.getName().equals("..\\"))
continue;
BufferedInputStream bin = new BufferedInputStream(zin);
byte[] buf = new byte[];
bin.read(buf,0,1);
}

2. 如何用java 将文件加密压缩为zip文件.

用java加密压缩zip文件:
package com.ninemax.demo.zip.decrypt;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.zip.DataFormatException;

import org.apache.commons.io.FileUtils;

import de.idyl.winzipaes.AesZipFileDecrypter;
import de.idyl.winzipaes.AesZipFileEncrypter;
import de.idyl.winzipaes.impl.AESDecrypter;
import de.idyl.winzipaes.impl.AESDecrypterBC;
import de.idyl.winzipaes.impl.AESEncrypter;
import de.idyl.winzipaes.impl.AESEncrypterBC;
import de.idyl.winzipaes.impl.ExtZipEntry;

/**
* 压缩指定文件或目录为ZIP格式压缩文件
* 支持中文(修改源码后)
* 支持密码(仅支持256bit的AES加密解密)
* 依赖bcprov项目(bcprov-jdk16-140.jar)
*
* @author zyh
*/
public class DecryptionZipUtil {

/**
* 使用指定密码将给定文件或文件夹压缩成指定的输出ZIP文件
* @param srcFile 需要压缩的文件或文件夹
* @param destPath 输出路径
* @param passwd 压缩文件使用的密码
*/
public static void zip(String srcFile,String destPath,String passwd) {
AESEncrypter encrypter = new AESEncrypterBC();
AesZipFileEncrypter zipFileEncrypter = null;
try {
zipFileEncrypter = new AesZipFileEncrypter(destPath, encrypter);
/**
* 此方法是修改源码后添加,用以支持中文文件名
*/
zipFileEncrypter.setEncoding("utf8");
File sFile = new File(srcFile);
/**
* AesZipFileEncrypter提供了重载的添加Entry的方法,其中:
* add(File f, String passwd)
* 方法是将文件直接添加进压缩文件
*
* add(File f, String pathForEntry, String passwd)
* 方法是按指定路径将文件添加进压缩文件
* pathForEntry - to be used for addition of the file (path within zip file)
*/
doZip(sFile, zipFileEncrypter, "", passwd);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
zipFileEncrypter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

/**
* 具体压缩方法,将给定文件添加进压缩文件中,并处理压缩文件中的路径
* @param file 给定磁盘文件(是文件直接添加,是目录递归调用添加)
* @param encrypter AesZipFileEncrypter实例,用于输出加密ZIP文件
* @param pathForEntry ZIP文件中的路径
* @param passwd 压缩密码
* @throws IOException
*/
private static void doZip(File file, AesZipFileEncrypter encrypter,
String pathForEntry, String passwd) throws IOException {
if (file.isFile()) {
pathForEntry += file.getName();
encrypter.add(file, pathForEntry, passwd);
return;
}
pathForEntry += file.getName() + File.separator;
for(File subFile : file.listFiles()) {
doZip(subFile, encrypter, pathForEntry, passwd);
}
}

/**
* 使用给定密码解压指定压缩文件到指定目录
* @param inFile 指定Zip文件
* @param outDir 解压目录
* @param passwd 解压密码
*/
public static void unzip(String inFile, String outDir, String passwd) {
File outDirectory = new File(outDir);
if (!outDirectory.exists()) {
outDirectory.mkdir();
}
AESDecrypter decrypter = new AESDecrypterBC();
AesZipFileDecrypter zipDecrypter = null;
try {
zipDecrypter = new AesZipFileDecrypter(new File(inFile), decrypter);
AesZipFileDecrypter.charset = "utf-8";
/**
* 得到ZIP文件中所有Entry,但此处好像与JDK里不同,目录不视为Entry
* 需要创建文件夹,entry.isDirectory()方法同样不适用,不知道是不是自己使用错误
* 处理文件夹问题处理可能不太好
*/
List<ExtZipEntry> entryList = zipDecrypter.getEntryList();
for(ExtZipEntry entry : entryList) {
String eName = entry.getName();
String dir = eName.substring(0, eName.lastIndexOf(File.separator) + 1);
File extractDir = new File(outDir, dir);
if (!extractDir.exists()) {
FileUtils.forceMkdir(extractDir);
}
/**
* 抽出文件
*/
File extractFile = new File(outDir + File.separator + eName);
zipDecrypter.extractEntry(entry, extractFile, passwd);
}
} catch (IOException e) {
e.printStackTrace();
} catch (DataFormatException e) {
e.printStackTrace();
} finally {
try {
zipDecrypter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

/**
* 测试
* @param args
*/
public static void main(String[] args) {
/**
* 压缩测试
* 可以传文件或者目录
*/
// zip("M:\\ZIP\\test\\bb\\a\\t.txt", "M:\\ZIP\\test\\temp1.zip", "zyh");
// zip("M:\\ZIP\\test\\bb", "M:\\ZIP\\test\\temp2.zip", "zyh");

unzip("M:\\ZIP\\test\\temp2.zip", "M:\\ZIP\\test\\temp", "zyh");
}
}
压缩多个文件时,有两个方法(第一种没试):
(1) 预先把多个文件压缩成zip,然后调用enc.addAll(inZipFile, password);方法将多个zip文件加进来。
(2)针对需要压缩的文件循环调用enc.add(inFile, password);,每次都用相同的密码。

3. 怎样用java快速实现zip文件的压缩解压缩

packagezip;
importjava.io.BufferedInputStream;
importjava.io.BufferedOutputStream;
importjava.io.File;
importjava.io.FileInputStream;
importjava.io.FileOutputStream;
importjava.util.Enumeration;
importjava.util.zip.CRC32;
importjava.util.zip.CheckedOutputStream;
importjava.util.zip.ZipEntry;
importjava.util.zip.ZipFile;
importjava.util.zip.ZipOutputStream;
importorg.apache.commons.lang3.StringUtils;
publicclassZipUtil{

/**
*递归压缩文件夹
*@paramsrcRootDir压缩文件夹根目录的子路径
*@paramfile当前递归压缩的文件或目录对象
*@paramzos压缩文件存储对象
*@throwsException
*/
privatestaticvoidzip(StringsrcRootDir,Filefile,ZipOutputStreamzos)throwsException
{
if(file==null)
{
return;
}

//如果是文件,则直接压缩该文件
if(file.isFile())
{
intcount,bufferLen=1024;
bytedata[]=newbyte[bufferLen];

//获取文件相对于压缩文件夹根目录的子路径
StringsubPath=file.getAbsolutePath();
intindex=subPath.indexOf(srcRootDir);
if(index!=-1)
{
subPath=subPath.substring(srcRootDir.length()+File.separator.length());
}
ZipEntryentry=newZipEntry(subPath);
zos.putNextEntry(entry);
BufferedInputStreambis=newBufferedInputStream(newFileInputStream(file));
while((count=bis.read(data,0,bufferLen))!=-1)
{
zos.write(data,0,count);
}
bis.close();
zos.closeEntry();
}
//如果是目录,则压缩整个目录
else
{
//压缩目录中的文件或子目录
File[]childFileList=file.listFiles();
for(intn=0;n<childFileList.length;n++)
{
childFileList[n].getAbsolutePath().indexOf(file.getAbsolutePath());
zip(srcRootDir,childFileList[n],zos);
}
}
}

/**
*对文件或文件目录进行压缩
*@paramsrcPath要压缩的源文件路径。如果压缩一个文件,则为该文件的全路径;如果压缩一个目录,则为该目录的顶层目录路径
*@paramzipPath压缩文件保存的路径。注意:zipPath不能是srcPath路径下的子文件夹
*@paramzipFileName压缩文件名
*@throwsException
*/
publicstaticvoidzip(StringsrcPath,StringzipPath,StringzipFileName)throwsException
{
if(StringUtils.isEmpty(srcPath)||StringUtils.isEmpty(zipPath)||StringUtils.isEmpty(zipFileName))
{
thrownewParameterException(ICommonResultCode.PARAMETER_IS_NULL);
}
CheckedOutputStreamcos=null;
ZipOutputStreamzos=null;
try
{
FilesrcFile=newFile(srcPath);

//判断压缩文件保存的路径是否为源文件路径的子文件夹,如果是,则抛出异常(防止无限递归压缩的发生)
if(srcFile.isDirectory()&&zipPath.indexOf(srcPath)!=-1)
{
thrownewParameterException(ICommonResultCode.INVALID_PARAMETER,".");
}

//判断压缩文件保存的路径是否存在,如果不存在,则创建目录
FilezipDir=newFile(zipPath);
if(!zipDir.exists()||!zipDir.isDirectory())
{
zipDir.mkdirs();
}

//创建压缩文件保存的文件对象
StringzipFilePath=zipPath+File.separator+zipFileName;
FilezipFile=newFile(zipFilePath);
if(zipFile.exists())
{
//检测文件是否允许删除,如果不允许删除,将会抛出SecurityException
=newSecurityManager();
securityManager.checkDelete(zipFilePath);
//删除已存在的目标文件
zipFile.delete();
}

cos=newCheckedOutputStream(newFileOutputStream(zipFile),newCRC32());
zos=newZipOutputStream(cos);

//如果只是压缩一个文件,则需要截取该文件的父目录
StringsrcRootDir=srcPath;
if(srcFile.isFile())
{
intindex=srcPath.lastIndexOf(File.separator);
if(index!=-1)
{
srcRootDir=srcPath.substring(0,index);
}
}
//调用递归压缩方法进行目录或文件压缩
zip(srcRootDir,srcFile,zos);
zos.flush();
}
catch(Exceptione)
{
throwe;
}
finally
{
try
{
if(zos!=null)
{
zos.close();
}
}
catch(Exceptione)
{
e.printStackTrace();
}
}
}

/**
*解压缩zip包
*@paramzipFilePathzip文件的全路径
*@paramunzipFilePath解压后的文件保存的路径
*@paramincludeZipFileName解压后的文件保存的路径是否包含压缩文件的文件名。true-包含;false-不包含
*/
@SuppressWarnings("unchecked")
publicstaticvoinzip(StringzipFilePath,StringunzipFilePath,booleanincludeZipFileName)throwsException
{
if(StringUtils.isEmpty(zipFilePath)||StringUtils.isEmpty(unzipFilePath))
{
thrownewParameterException(ICommonResultCode.PARAMETER_IS_NULL);
}
FilezipFile=newFile(zipFilePath);
//如果解压后的文件保存路径包含压缩文件的文件名,则追加该文件名到解压路径
if(includeZipFileName)
{
StringfileName=zipFile.getName();
if(StringUtils.isNotEmpty(fileName))
{
fileName=fileName.substring(0,fileName.lastIndexOf("."));
}
unzipFilePath=unzipFilePath+File.separator+fileName;
}
//创建解压缩文件保存的路径
FileunzipFileDir=newFile(unzipFilePath);
if(!unzipFileDir.exists()||!unzipFileDir.isDirectory())
{
unzipFileDir.mkdirs();
}

//开始解压
ZipEntryentry=null;
StringentryFilePath=null,entryDirPath=null;
FileentryFile=null,entryDir=null;
intindex=0,count=0,bufferSize=1024;
byte[]buffer=newbyte[bufferSize];
BufferedInputStreambis=null;
BufferedOutputStreambos=null;
ZipFilezip=newZipFile(zipFile);
Enumeration<ZipEntry>entries=(Enumeration<ZipEntry>)zip.entries();
//循环对压缩包里的每一个文件进行解压
while(entries.hasMoreElements())
{
entry=entries.nextElement();
//构建压缩包中一个文件解压后保存的文件全路径
entryFilePath=unzipFilePath+File.separator+entry.getName();
//构建解压后保存的文件夹路径
index=entryFilePath.lastIndexOf(File.separator);
if(index!=-1)
{
entryDirPath=entryFilePath.substring(0,index);
}
else
{
entryDirPath="";
}
entryDir=newFile(entryDirPath);
//如果文件夹路径不存在,则创建文件夹
if(!entryDir.exists()||!entryDir.isDirectory())
{
entryDir.mkdirs();
}

//创建解压文件
entryFile=newFile(entryFilePath);
if(entryFile.exists())
{
//检测文件是否允许删除,如果不允许删除,将会抛出SecurityException
=newSecurityManager();
securityManager.checkDelete(entryFilePath);
//删除已存在的目标文件
entryFile.delete();
}

//写入文件
bos=newBufferedOutputStream(newFileOutputStream(entryFile));
bis=newBufferedInputStream(zip.getInputStream(entry));
while((count=bis.read(buffer,0,bufferSize))!=-1)
{
bos.write(buffer,0,count);
}
bos.flush();
bos.close();
}
}

publicstaticvoidmain(String[]args)
{
StringzipPath="d:\ziptest\zipPath";
Stringdir="d:\ziptest\rawfiles";
StringzipFileName="test.zip";
try
{
zip(dir,zipPath,zipFileName);
}
catch(Exceptione)
{
e.printStackTrace();
}

StringzipFilePath="D:\ziptest\zipPath\test.zip";
StringunzipFilePath="D:\ziptest\zipPath";
try
{
unzip(zipFilePath,unzipFilePath,true);
}
catch(Exceptione)
{
e.printStackTrace();
}
}
}

4. 如何在java中执行zip压缩命令

publicclassZipFile{

publicstaticvoidmain(String[]args)throwsException{
//zip-rqq.zipWEB-INF-x'*.DS_Store'

ZipFilezipFile=newZipFile();
zipFile.start("zip-rqq.zipWEB-INF-x'*.DS_Store'");
}

privatesynchronizedvoidstart(Stringcmd)throwsException{
Processpro=null;
pro=Runtime.getRuntime().exec(cmd);
newDoOutput(pro.getInputStream()).start();
newDoOutput(pro.getErrorStream()).start();
}

{
publicInputStreamis;
publicDoOutput(InputStreamis){
this.is=is;
}
publicvoidrun(){
BufferedReaderbr=newBufferedReader(newInputStreamReader(this.is));
Stringstr=null;
StringBuildersb=newStringBuilder();
try{
while((str=br.readLine())!=null){
sb.append(str+" ");
}
System.out.println(sb.toString());
}catch(Exceptione){
e.printStackTrace();
}finally{
if(br!=null){
try{
br.close();
}catch(Exceptione){
e.printStackTrace();
}
}
}
}
}

}

5. 如何使用java压缩文件夹成为zip包(最简单的

import java.io.File;

public class ZipCompressorByAnt {

private File zipFile;

/**
* 压缩文件构造函数
* @param pathName 最终压缩生成的压缩文件:目录+压缩文件名.zip
*/
public ZipCompressorByAnt(String finalFile) {
zipFile = new File(finalFile);
}

/**
* 执行压缩操作
* @param srcPathName 需要被压缩的文件/文件夹
*/
public void compressExe(String srcPathName) {
System.out.println("srcPathName="+srcPathName);

File srcdir = new File(srcPathName);
if (!srcdir.exists()){
throw new RuntimeException(srcPathName + "不存在!");
}

Project prj = new Project();
Zip zip = new Zip();
zip.setProject(prj);
zip.setDestFile(zipFile);
FileSet fileSet = new FileSet();
fileSet.setProject(prj);
fileSet.setDir(srcdir);
//fileSet.setIncludes("**/*.java"); //包括哪些文件或文件夹 eg:zip.setIncludes("*.java");
//fileSet.setExcludes(...); //排除哪些文件或文件夹
zip.addFileset(fileSet);
zip.execute();
}

}

public class TestZip {

public static void main(String[] args) {

ZipCompressorByAnt zca = new ZipCompressorByAnt("E:\test1.zip ");
zca.compressExe("E:\test1");
}

}

/*如果 出现ant 的 52 51 50 等版本问题 可以去找对应的ant-1.8.2.jar 我开始用的ant-1.10.1.jar 就是这个包版本高了 一直报verson 52 版本问题*/

6. java 以流的形式解压带密码的zip

可以使用 Runtime 直接调用 winRar 的命令行命令来解压缩
注意:
1、winRar命令使用,在dos下输入 unrar 就可以看到全部的命令说明。该命令在winRar的安装目录下
2、winRar命令行命令的路径问题,也就是path。要么加入系统变量path中,要么在winRar的安装目录下执行程序
以下是程序代码,解压 test.rar 到当前目录下,密码123

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;

public class TestRunTime {

public static void main(String[] args) {
Runtime run = Runtime.getRuntime();
try {
Process p = run.exec("unrar e test.rar -p123");//执行解压缩命令
BufferedInputStream in = new BufferedInputStream(p.getInputStream());
BufferedReader inBr = new BufferedReader(new InputStreamReader(in));
String lineStr;

while ((lineStr = inBr.readLine()) != null)
System.out.println(lineStr);
// 检查命令是否执行失败。
if (p.waitFor() != 0) {
if (p.exitValue() == 1)// p.exitValue()==0表示正常结束,1:非正常结束
System.err.println("命令执行失败!");
}

} catch (Exception e) {
e.printStackTrace();
}

}

}

7. java压缩文件的问题

有三种方式实现java压缩:

1、jdk自带的包java.util.zip.ZipOutputStream,不足之处,文件(夹)名称带中文时,出现乱码问题,实现代码如下:
/**
* 功能:把 sourceDir 目录下的所有文件进行 zip 格式的压缩,保存为指定 zip 文件
* @param sourceDir 如果是目录,eg:D:\\MyEclipse\\first\\testFile,则压缩目录下所有文件;
* 如果是文件,eg:D:\\MyEclipse\\first\\testFile\\aa.zip,则只压缩本文件
* @param zipFile 最后压缩的文件路径和名称,eg:D:\\MyEclipse\\first\\testFile\\aa.zip
*/
public File doZip(String sourceDir, String zipFilePath) throws IOException {
File file = new File(sourceDir);
File zipFile = new File(zipFilePath);
ZipOutputStream zos = null;
try {
// 创建写出流操作
OutputStream os = new FileOutputStream(zipFile);
BufferedOutputStream bos = new BufferedOutputStream(os);
zos = new ZipOutputStream(bos);

String basePath = null;

// 获取目录
if(file.isDirectory()) {
basePath = file.getPath();
}else {
basePath = file.getParent();
}

zipFile(file, basePath, zos);
}finally {
if(zos != null) {
zos.closeEntry();
zos.close();
}
}

return zipFile;
}
/**
* @param source 源文件
* @param basePath
* @param zos
*/
private void zipFile(File source, String basePath, ZipOutputStream zos)
throws IOException {
File[] files = null;
if (source.isDirectory()) {
files = source.listFiles();
} else {
files = new File[1];
files[0] = source;
}

InputStream is = null;
String pathName;
byte[] buf = new byte[1024];
int length = 0;
try{
for(File file : files) {
if(file.isDirectory()) {
pathName = file.getPath().substring(basePath.length() + 1) + "/";
zos.putNextEntry(new ZipEntry(pathName));
zipFile(file, basePath, zos);
}else {
pathName = file.getPath().substring(basePath.length() + 1);
is = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(is);
zos.putNextEntry(new ZipEntry(pathName));
while ((length = bis.read(buf)) > 0) {
zos.write(buf, 0, length);
}
}
}
}finally {
if(is != null) {
is.close();
}
}
}

2、使用org.apache.tools.zip.ZipOutputStream,代码如下,
package net.szh.zip;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.CRC32;
import java.util.zip.CheckedOutputStream;

import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipOutputStream;

public class ZipCompressor {
static final int BUFFER = 8192;

private File zipFile;

public ZipCompressor(String pathName) {
zipFile = new File(pathName);
}

public void compress(String srcPathName) {
File file = new File(srcPathName);
if (!file.exists())
throw new RuntimeException(srcPathName + "不存在!");
try {
FileOutputStream fileOutputStream = new FileOutputStream(zipFile);
CheckedOutputStream cos = new CheckedOutputStream(fileOutputStream,
new CRC32());
ZipOutputStream out = new ZipOutputStream(cos);
String basedir = "";
compress(file, out, basedir);
out.close();
} catch (Exception e) {
throw new RuntimeException(e);
}
}

private void compress(File file, ZipOutputStream out, String basedir) {
/* 判断是目录还是文件 */
if (file.isDirectory()) {
System.out.println("压缩:" + basedir + file.getName());
this.compressDirectory(file, out, basedir);
} else {
System.out.println("压缩:" + basedir + file.getName());
this.compressFile(file, out, basedir);
}
}

/** 压缩一个目录 */
private void compressDirectory(File dir, ZipOutputStream out, String basedir) {
if (!dir.exists())
return;

File[] files = dir.listFiles();
for (int i = 0; i < files.length; i++) {
/* 递归 */
compress(files[i], out, basedir + dir.getName() + "/");
}
}

/** 压缩一个文件 */
private void compressFile(File file, ZipOutputStream out, String basedir) {
if (!file.exists()) {
return;
}
try {
BufferedInputStream bis = new BufferedInputStream(
new FileInputStream(file));
ZipEntry entry = new ZipEntry(basedir + file.getName());
out.putNextEntry(entry);
int count;
byte data[] = new byte[BUFFER];
while ((count = bis.read(data, 0, BUFFER)) != -1) {
out.write(data, 0, count);
}
bis.close();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}

3、可以用ant中的org.apache.tools.ant.taskdefs.Zip来实现,更加简单。
package net.szh.zip;

import java.io.File;

import org.apache.tools.ant.Project;
import org.apache.tools.ant.taskdefs.Zip;
import org.apache.tools.ant.types.FileSet;

public class ZipCompressorByAnt {

private File zipFile;

public ZipCompressorByAnt(String pathName) {
zipFile = new File(pathName);
}

public void compress(String srcPathName) {
File srcdir = new File(srcPathName);
if (!srcdir.exists())
throw new RuntimeException(srcPathName + "不存在!");

Project prj = new Project();
Zip zip = new Zip();
zip.setProject(prj);
zip.setDestFile(zipFile);
FileSet fileSet = new FileSet();
fileSet.setProject(prj);
fileSet.setDir(srcdir);
//fileSet.setIncludes("**/*.java"); 包括哪些文件或文件夹 eg:zip.setIncludes("*.java");
//fileSet.setExcludes(...); 排除哪些文件或文件夹
zip.addFileset(fileSet);

zip.execute();
}
}
测试一下
package net.szh.zip;

public class TestZip {
public static void main(String[] args) {
ZipCompressor zc = new ZipCompressor("E:\\szhzip.zip");
zc.compress("E:\\test");

ZipCompressorByAnt zca = new ZipCompressorByAnt("E:\\szhzipant.zip");
zca.compress("E:\\test");
}
}

8. java编写的代码怎么压缩成zip文件

摘要 (1)可以压缩文件,也可以压缩文件夹

9. java如何实现md5加密的压缩为zip

public class ZipUtil {
private static final String ALGORITHM = "PBEWithMD5AndDES";
private static Logger logger = Logger.getLogger(ZipUtil.class);
public static void zip(String zipFileName, String inputFile,String pwd) throws Exception {
zip(zipFileName, new File(inputFile), pwd);
}

/**
* 功能描述:压缩指定路径下的所有文件
* @param zipFileName 压缩文件名(带有路径)
* @param inputFile 指定压缩文件夹
* @return
* @throws Exception
*/
public static void zip(String zipFileName, String inputFile) throws Exception {
zip(zipFileName, new File(inputFile), null);
}
/**
* 功能描述:压缩文件对象
* @param zipFileName 压缩文件名(带有路径)
* @param inputFile 文件对象
* @return
* @throws Exception
*/
public static void zip(String zipFileName, File inputFile,String pwd) throws Exception {
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFileName));
zip(out, inputFile, "",pwd);
out.close();
}
/**
*
* @param out 压缩输出流对象
* @param file
* @param base
* @throws Exception
*/
public static void zip(ZipOutputStream outputStream, File file, String base,String pwd) throws Exception {
if (file.isDirectory()) {
File[] fl = file.listFiles();
outputStream.putNextEntry(new ZipEntry(base + "/"));
base = base.length() == 0 ? "" : base + "/";
for (int i = 0; i < fl.length; i++) {
zip(outputStream, fl[i], base + fl[i].getName(), pwd);
}
}
else {
outputStream.putNextEntry(new ZipEntry(base));
FileInputStream inputStream = new FileInputStream(file);
//普通压缩文件
if(pwd == null || pwd.trim().equals("")){
int b;
while ((b = inputStream.read()) != -1){
outputStream.write(b);
}
inputStream.close();
}
//给压缩文件加密
else{
PBEKeySpec keySpec = new PBEKeySpec(pwd.toCharArray());
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(ALGORITHM);
SecretKey passwordKey = keyFactory.generateSecret(keySpec);
byte[] salt = new byte[8];
Random rnd = new Random();
rnd.nextBytes(salt);
int iterations = 100;
PBEParameterSpec parameterSpec = new PBEParameterSpec(salt, iterations);
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, passwordKey, parameterSpec);
outputStream.write(salt);
byte[] input = new byte[64];
int bytesRead;
while ((bytesRead = inputStream.read(input)) != -1) {
byte[] output = cipher.update(input, 0, bytesRead);
if (output != null){
outputStream.write(output);
}
}
byte[] output = cipher.doFinal();
if (output != null){
outputStream.write(output);
}
inputStream.close();
outputStream.flush();
outputStream.close();
}
}
file.delete();
}

public static void unzip(String zipFileName, String outputDirectory)throws Exception {
ZipInputStream inputStream = new ZipInputStream(new FileInputStream(zipFileName));
unzip(inputStream, outputDirectory, null);
}

/**
* 功能描述:将压缩文件解压到指定的文件目录下
* @param zipFileName 压缩文件名称(带路径)
* @param outputDirectory 指定解压目录
* @return
* @throws Exception
*/
public static void unzip(String zipFileName, String outputDirectory, String pwd)throws Exception {
ZipInputStream inputStream = new ZipInputStream(new FileInputStream(zipFileName));
unzip(inputStream, outputDirectory, pwd);
}

public static void unzip(File zipFile, String outputDirectory, String pwd)throws Exception {
ZipInputStream inputStream = new ZipInputStream(new FileInputStream(zipFile));
unzip(inputStream, outputDirectory,pwd);
}

public static void unzip(ZipInputStream inputStream, String outputDirectory, String pwd) throws Exception{
ZipEntry zipEntry = null;
FileOutputStream outputStream = null;
try{
while ((zipEntry = inputStream.getNextEntry()) != null) {
if (zipEntry.isDirectory()) {
String name = zipEntry.getName();
name = name.substring(0, name.length() - 1);
File file = new File(outputDirectory + File.separator + name);
if(! file.exists()){
file.mkdirs();
}
}else {
File file = new File(outputDirectory + File.separator + zipEntry.getName());
File parentFile = file.getParentFile();
if(! parentFile.exists()){
parentFile.mkdirs();
}
file.createNewFile();
outputStream = new FileOutputStream(file);
if(pwd == null || pwd.trim().equals("")){
int b;
byte[] buffer = new byte[1024];
while ((b = inputStream.read(buffer)) != -1){
outputStream.write(buffer);
}
outputStream.flush();
}else{
PBEKeySpec keySpec = new PBEKeySpec(pwd.toCharArray());
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(ALGORITHM);
SecretKey passwordKey = keyFactory.generateSecret(keySpec);
byte[] salt = new byte[8];
inputStream.read(salt);
int iterations = 100;
PBEParameterSpec parameterSpec = new PBEParameterSpec(salt, iterations);
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, passwordKey, parameterSpec);
byte[] input = new byte[64];
int bytesRead;
while ((bytesRead = inputStream.read(input)) != -1) {
byte[] output = cipher.update(input, 0, bytesRead);
if (output != null){
outputStream.write(output);
}
}
byte[] output = cipher.doFinal();
if (output != null){
outputStream.write(output);
}
outputStream.flush();
}
}
}
}
catch(IOException ex){
logger.error(ex);
throw ex;
}catch(Exception ex){
logger.error(ex);
throw ex;
}finally{
if(inputStream != null){
inputStream.close();
}
if(outputStream != null){
outputStream.close();
}

}
}

public static byte[] getByteArrayFromFile(String fileName) throws Exception{
FileInputStream fi = null;
try{
File file = new File(fileName);
long size = file.length();
if (size > Integer.MAX_VALUE) {
throw new Exception("文件太大");
}
fi = new FileInputStream(file);
byte[] buffer = new byte[1024];
byte[] all = new byte[(int) size];
int offset = 0;
int len = 0;
while ((len = fi.read(buffer)) > -1) {
System.array(buffer, 0, all, offset, len);
offset += len;
}
return all;
}catch(Exception ex){
logger.error(ex);
throw ex;
}finally{
if(fi != null){
fi.close();
}
}
}
public static void createFileFromByteArray(byte[] b,String destName) throws Exception{
FileOutputStream os = null;
try{
File destFile = new File(destName);
File parentFile = destFile.getParentFile();
if(! parentFile.exists()){
parentFile.mkdirs();
}
os = new FileOutputStream(destName);
os.write(b);
os.flush();
}catch(Exception e){
logger.error(e);
throw e;
}finally{
if(os != null){
os.close();
}
}

}
public static void main(String[] args) throws Exception{
String fileName = "E:\\sunjinfu\\test\\test.zip";
String outputDir = "E:\\sunjinfu\\test\\csv\\123";
unzip(fileName, outputDir);
}

自己好好研究一下,我只用了其中一部分,你需要就调试调试,也许会有点错误。

10. JAVA解压缩ZIP包问题:

我试了一下,没有问题
先问一下,你用的JDK是什么版 本。我是1.6_20,直接用你的程序。
zipFile = new ZipFile(new File(zipfile),"GBK");
Enumeration enumeration = zipFile.getEntries();
是报错的。
我改成了
zipFile = new ZipFile(new File(zipfile));
Enumeration enumeration = zipFile.entries();

这应该不是主要问题。

有没有可能是你的压缩包损坏了。或是包里的那个文件坏了,跟一下断点,看一下是解那个文件出的错。

热点内容
有什么推荐的网游低配置 发布:2024-10-08 03:17:03 浏览:36
淘优惠源码 发布:2024-10-08 03:17:02 浏览:780
linux系统制作 发布:2024-10-08 02:47:15 浏览:252
4s缓存怎么清理 发布:2024-10-08 02:46:42 浏览:429
苹果11面容存储微信密码 发布:2024-10-08 02:35:58 浏览:764
魔兽243脚本 发布:2024-10-08 02:35:12 浏览:640
在团竞模式中怎么重置配置 发布:2024-10-08 02:12:54 浏览:292
宝马远程服务器如何启用 发布:2024-10-08 02:02:57 浏览:391
c语言freadfwrite 发布:2024-10-08 02:01:15 浏览:854
脚本还不简单吗 发布:2024-10-08 01:54:43 浏览:423