當前位置:首頁 » 文件管理 » 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 04:19:05 瀏覽:420
seer資料庫 發布:2024-10-08 04:18:47 瀏覽:477
l3緩存分數下降 發布:2024-10-08 04:10:36 瀏覽:433
linux游戲伺服器 發布:2024-10-08 04:04:17 瀏覽:74
有什麼推薦的網游低配置 發布: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