利用Java实现zip压缩与解压缩【青鸟资源分享】

合集下载

JavaZIP压缩和解压缩文件(解决中文文件名乱码问题)

JavaZIP压缩和解压缩文件(解决中文文件名乱码问题)

JavaZIP压缩和解压缩⽂件(解决中⽂⽂件名乱码问题)JDK中⾃带的ZipOutputStream在压缩⽂件时,如果⽂件名中有中⽂,则压缩后的zip⽂件打开时发现中⽂⽂件名变成乱码.解决的⽅法是使⽤apache-ant-zip.jar包(见附件)中的ZipOutputStream和ZipEntry.即,导⼊类:import org.apache.tools.zip.ZipEntry;import org.apache.tools.zip.ZipOutputStream;并且注意,压缩之前调⽤ZipOutputStream的out.setEncoding(System.getProperty("sun.jnu.encoding"));⽅法,系统参数sun.jnu.encoding表⽰获取当前系统中的⽂件名的编码⽅式.这⾥将ZipOutputStream的⽂件名编码⽅式设置成系统的⽂件名编码⽅式.解压时,直接使⽤JDK原来的ZipInputStream即可.但是有个需要注意的地⽅是,在读取ZIP⽂件之前,需要设置:System.setProperty("sun.zip.encoding", System.getProperty("sun.jnu.encoding"));将系统的ZIP编码格式设置为系统⽂件名编码⽅式,否则解压时报异常.import java.util.zip.ZipEntry;import java.util.zip.ZipOutputStream;改为import org.apache.tools.zip.ZipEntry;import org.apache.tools.zip.ZipOutputStream;ant包⾥提供ZipOutputStream类的setEncoding("gbk")⽅法。

zos.setEncoding("gbk");。

利用java实现zip的压缩和解压

利用java实现zip的压缩和解压

menuitem neww= new menuitem("new");
neww.addactionlistener(this);
file.add(neww);
menuitem open=new menuitem("open");
open.addactionlistener(this);
dispose();∥关闭窗口
system.exit(0);∥关闭程序
}
else {
system.out.println("no this command!");
}
}
}
if ("new".equals(arg)) randomdata();
else if ("open".equals(arg)) openfile();
else if ("save".equals(arg)) savefile();
else if ("exit".equals(arg)){
∥用zip输入流构建datainputstream
doc=dis.readutf();∥读取文件内容
dis.close();∥关闭文件
doczipsize = f.length();∥获取zip文件长度
showtextandinfo();∥显示数据
exit.addactionlistener(this);
file.add(exit);
∥随机生成的数据文件的多行文本显示域
add("center",textarea = new textarea());

用Java进行zip文件压缩与解压缩

用Java进行zip文件压缩与解压缩

⽤Java进⾏zip⽂件压缩与解压缩可能存在的业务情况:1、⽤户上传了压缩包,需校验压缩包中的⽂件是否合格。

2、⽤户上传压缩包,对压缩包中的⽂件进⾏批量⽔印处理解决思路:1、读取原压缩包⽂件,解压缩⾄临时⽬录2、对临时⽬录中的解压缩⽂件进⾏校验/⽔印处理3、对临时⽬录中处理过的⽂件进⾏压缩4、删除临时⽬录及其下的⽂件需要参考前⾯的校验PDF的帖⼦测试结果如下:测试代码:@Testpublic void testZip() {String filePath = "D:\\pdfTest\\合格压缩⽂件.zip";// 获取原⽂所在⽬录// 服务器上时,⽂件路径为“/”,此处测试需要换成filePath中的“\\”//String oldFilePath = filePath.substring(0, stIndexOf("/"));String oldFilePath = filePath.substring(0, stIndexOf("\\"));System.out.println("原⽂件路径:" + oldFilePath);// 临时⽬录,原压缩⽂件解压⽬录String destDirPath = oldFilePath + "\\tmp\\";System.out.println("临时路径:" + destDirPath);// 将原压缩⽂件解压到临时⽬录ZipUtil.unzipFile(filePath, destDirPath);// 临时⽬录⽂件对象File destDir = new File(destDirPath);// 获取临时⽬录下的所有⽂件File[] files = destDir.listFiles();// 定义变量,保存校验结果List<Integer> list = new ArrayList<>();// 遍历⽂件,进⾏校验for (File file: files) {String absolutePath = file.getAbsolutePath();System.out.println(absolutePath);int i = CheckPdfHelper.checkPdf(absolutePath);list.add(i);// 压缩包中存在不合格PDF⽂件时if (i != 0) {break;}}// 判断是否包含不合格PDF⽂件if (list.contains(1)) {System.out.println("压缩⽂件中包含不合格PDF⽂件");// 删除解压缩的⽂件和临时⽬录ZipUtil.deletefile(destDirPath);// 不合格时,不⽣成新的压缩包⽂件return;} else {System.out.println("压缩⽂件PDF⽂件均符合要求");}// 获取原压缩⽂件后缀int pos = stIndexOf('.');String suffix = filePath.substring(pos + 1);// 新⽣成压缩⽂件路径String newFilePath = filePath.substring(0, pos) + ".PSW." + suffix;System.out.println("新的压缩⽂件路径:" + newFilePath);// 将检验成功的⽂件压缩成⼀个新的压缩包ZipUtil.zipFile(newFilePath, files);// 删除临时⽬录ZipUtil.deletefile(destDirPath);}ZipUtil⼯具类:package com.alphajuns.util;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.util.ArrayList;import java.util.Enumeration;import java.util.List;import org.apache.tools.zip.ZipEntry;import org.apache.tools.zip.ZipFile;import org.apache.tools.zip.ZipOutputStream;/*** @ClassName ZipUtil* @Description 压缩或解压缩zip:由于直接使⽤java.util.zip⼯具包下的类,会出现中⽂乱码问题,所以使⽤ant.jar中的org.apache.tools.zip下的⼯具类 * @Author AlphaJunS* @Date 2020/3/8 11:30* @Version 1.0*/public class ZipUtil {/*** @Author AlphaJunS* @Date 11:32 2020/3/8* @Description* @param zip 压缩⽬的地址* @param srcFiles 压缩的源⽂件* @return void*/public static void zipFile( String zip , File[] srcFiles ) {try {if( zip.endsWith(".zip") || zip.endsWith(".ZIP") ){FileOutputStream fos = new FileOutputStream(new File(zip));ZipOutputStream _zipOut = new ZipOutputStream(fos) ;_zipOut.setEncoding("GBK");for( File _f : srcFiles ){handlerFile(zip , _zipOut , _f , "");}fos.close();_zipOut.close();}else{System.out.println("target file[" + zip + "] is not .zip type file");}} catch (FileNotFoundException e) {} catch (IOException e) {}}/*** @Author AlphaJunS* @Date 11:33 2020/3/8* @Description* @param zip 压缩的⽬的地址* @param zipOut* @param srcFile 被压缩的⽂件信息* @param path 在zip中的相对路径* @return void*/private static void handlerFile(String zip , ZipOutputStream zipOut , File srcFile , String path) throws IOException {System.out.println(" begin to compression file[" + srcFile.getName() + "]");if( !"".equals(path) && ! path.endsWith(File.separator)){path += File.separator ;}if( ! srcFile.getPath().equals(zip) ){if( srcFile.isDirectory() ){File[] _files = srcFile.listFiles() ;if( _files.length == 0 ){zipOut.putNextEntry(new ZipEntry( path + srcFile.getName() + File.separator)); zipOut.closeEntry();}else{for( File _f : _files ){handlerFile( zip ,zipOut , _f , path + srcFile.getName() );}}}else{InputStream _in = new FileInputStream(srcFile) ;zipOut.putNextEntry(new ZipEntry(path + srcFile.getName()));int len = 0 ;byte[] _byte = new byte[1024];while( (len = _in.read(_byte)) > 0 ){zipOut.write(_byte, 0, len);}_in.close();zipOut.closeEntry();}}}/*** @Author AlphaJunS* @Date 11:34 2020/3/8* @Description 解压缩ZIP⽂件,将ZIP⽂件⾥的内容解压到targetDIR⽬录下* @param zipPath 待解压缩的ZIP⽂件名* @param descDir ⽬标⽬录* @return java.util.List<java.io.File>*/public static List<File> unzipFile(String zipPath, String descDir) {return unzipFile(new File(zipPath) , descDir) ;}/*** @Author AlphaJunS* @Date 11:36 2020/3/8* @Description 对.zip⽂件进⾏解压缩* @param zipFile 解压缩⽂件* @param descDir 压缩的⽬标地址,如:D:\\测试或 /mnt/d/测试* @return java.util.List<java.io.File>*/@SuppressWarnings("rawtypes")public static List<File> unzipFile(File zipFile, String descDir) {List<File> _list = new ArrayList<File>() ;try {ZipFile _zipFile = new ZipFile(zipFile , "GBK") ;for( Enumeration entries = _zipFile.getEntries() ; entries.hasMoreElements() ; ){ ZipEntry entry = (ZipEntry)entries.nextElement() ;File _file = new File(descDir + File.separator + entry.getName()) ;if( entry.isDirectory() ){_file.mkdirs() ;}else{File _parent = _file.getParentFile() ;if( !_parent.exists() ){_parent.mkdirs() ;}InputStream _in = _zipFile.getInputStream(entry);OutputStream _out = new FileOutputStream(_file) ;int len = 0 ;byte[] _byte = new byte[1024];while( (len = _in.read(_byte)) > 0){_out.write(_byte, 0, len);}_in.close();_out.flush();_out.close();_list.add(_file) ;}}} catch (IOException e) {}return _list ;}/*** @Author AlphaJunS* @Date 11:36 2020/3/8* @Description 对临时⽣成的⽂件夹和⽂件夹下的⽂件进⾏删除* @param delpath* @return void*/public static void deletefile(String delpath) {try {File file = new File(delpath);if (!file.isDirectory()) {file.delete();} else if (file.isDirectory()) {String[] fileList = file.list();for (int i = 0; i < fileList.length; i++) {File delfile = new File(delpath + File.separator + fileList[i]);if (!delfile.isDirectory()) {delfile.delete();} else if (delfile.isDirectory()) {deletefile(delpath + File.separator + fileList[i]);}}file.delete();}} catch (Exception e) {e.printStackTrace();}}}以上就是⽤Java进⾏zip⽂件压缩与解压缩的详细内容,更多关于java zip⽂件压缩与解压缩的资料请关注其它相关⽂章!。

Java实现对zip和rar文件的解压缩

Java实现对zip和rar文件的解压缩

Java实现对zip和rar⽂件的解压缩通过java实现对zip和rar⽂件的解压缩1package com.svse.test;2import java.io.File;3import java.io.FileOutputStream;4import java.io.IOException;5import java.io.InputStream;6import java.io.OutputStream;7import java.util.Enumeration;8import org.apache.tools.zip.ZipEntry;9import org.apache.tools.zip.ZipFile;10import de.innosystec.unrar.Archive;11import de.innosystec.unrar.rarfile.FileHeader;12/**13* zip和rar解压缩⼯具类14* @author lenovo15*16*/17public class ZipAndRarTools {18/**19 * 解压rar20 * @param sourceRarPath 需要解压的rar⽂件全路径21 * @param destDirPath 需要解压到的⽂件⽬录22 * @throws Exception23*/24public static void unrar(String sourceRarPath, String destDirPath) throws Exception {25 File sourceRar=new File(sourceRarPath);26 File destDir=new File(destDirPath);27 Archive archive = null;28 FileOutputStream fos = null;29 System.out.println("Starting 开始解压...");30 try {31 archive = new Archive(sourceRar);32 FileHeader fh = archive.nextFileHeader();33 int count = 0;34 File destFileName = null;35 while (fh != null) {36 System.out.println((++count) + ") " + fh.getFileNameString());37 String compressFileName = fh.getFileNameString().trim();38 destFileName = new File(destDir.getAbsolutePath() + "/" + compressFileName);39 if (fh.isDirectory()) {40 if (!destFileName.exists()) {41 destFileName.mkdirs();42 }43 fh = archive.nextFileHeader();44 continue;45 }46 if (!destFileName.getParentFile().exists()) {47 destFileName.getParentFile().mkdirs();48 }4950 fos = new FileOutputStream(destFileName);51 archive.extractFile(fh, fos);52 fos.close();53 fos = null;54 fh = archive.nextFileHeader();55 }5657 archive.close();58 archive = null;59 System.out.println("Finished 解压完成!");60 } catch (Exception e) {61throw e;62 } finally {63if (fos != null) {64try {65 fos.close();66 fos = null;67 } catch (Exception e) {68 }69 }70if (archive != null) {71try {72 archive.close();73 archive = null;74 } catch (Exception e) {75 }76 }77 }78 }798081/**82 * 解压Zip⽂件83 * @param zipFileName 需要解压缩的⽂件位置84 * @param descFileName 将⽂件解压到某个路径85 * @throws IOException86*/87public static void unZip(String zipFileName,String descFileName) throws IOException{88 System.out.println("⽂件解压开始...");89 String descFileNames=descFileName;90if(!descFileNames.endsWith(File.separator)){91 descFileNames=descFileNames+File.separator;92 }93try {94 ZipFile zipFile=new ZipFile(zipFileName);95 ZipEntry entry=null;96 String entryName=null;97 String descFileDir=null;98 byte[] buf=new byte[4096];99 int readByte=0;100 @SuppressWarnings("rawtypes")101 Enumeration enums=zipFile.getEntries();102 while(enums.hasMoreElements()){103 entry =(ZipEntry) enums.nextElement();104 entryName=entry.getName();105 descFileDir=descFileNames+entryName;106 if(entry.isDirectory()){107 new File(descFileDir).mkdir();108 continue;109 }else{110 new File(descFileDir).getParentFile().mkdir();111 }112 File file=new File(descFileDir);113 OutputStream os=new FileOutputStream(file);114 InputStream is=zipFile.getInputStream(entry);115while((readByte=is.read(buf))!=-1){116 os.write(buf, 0, readByte);117 }118 os.close();119 is.close();120 }121 zipFile.close();122 System.out.println("⽂件解压成功!");123 } catch (Exception e) {124 System.out.println("⽂件解压失败!");125 e.printStackTrace();126 }127128 }129130public static void main(String[] args) throws Exception {131//ZipAndRarTools.unrar(newFile("D:\\存放资料的压缩包\\员⼯材料.rar"),newFile("D:\\存放资料的⾮压缩包\\")); 132133 ZipAndRarTools.unZip("D:\\rarTest\\jar包和配置⽂件资源.zip", "D:\\rarTest");134 ZipAndRarTools.unrar("D:\\rarTest\\rar压缩包.rar", "D:\\rarTest");135136 }137 }。

Java中zip的压缩和解压缩的实现代码

Java中zip的压缩和解压缩的实现代码

Java中zip的压缩和解压缩的实现代码在Java中可以使⽤ZipOutputStream和ZipInputStream来实现zip的压缩和解压缩操作,另外使⽤FileSystem也可以⽤来实现zip的解压缩,下⾯将介绍这⼏种⽅式,直接上代码。

zip压缩待压缩⽂件⽬录结构:每个zip⽂件项都要对应⼀个ZipEntry,然后通过ZipOutputStream的putNextEntry⽅法开始写⼊⼀个新的zip⽂件项,将⽂件数据发送到zip输出流中,完成后再调⽤closeEntry⽅法。

@Testpublic void testCompressByZip() {try (//指定压缩完成后zip⽂件的存储路径ZipOutputStream zipOutputStream = new ZipOutputStream(new FileOutputStream("F:\\myFavorites.zip"))){//待压缩⽂件/⽬录所在的⽬录File fileFolder = new File("F:\\我的收藏");//获取⽬录下的所有⽂件File[] files = fileFolder.listFiles();ZipEntry zipEntry;byte[] byteArray;int len;//遍历⽬录下的所有⽂件/⽬录,并将它们添加到压缩⽂件中for (File file : files) {//⼀个ZipEntry对应压缩⽂件中的⼀项zipEntry = new ZipEntry(file.getName());zipOutputStream.putNextEntry(zipEntry);try (FileInputStream in = new FileInputStream(file)) {byteArray = new byte[1024];while ((len = in.read(byteArray)) != -1) {zipOutputStream.write(byteArray, 0, len);}} catch (IOException ex) {ex.printStackTrace();}zipOutputStream.closeEntry();}} catch (IOException ex) {ex.printStackTrace();}}压缩结果:zip解压缩遍历zip⽂件中的所有项,并获取对应项的输⼊流,然后通过FileOutputStream输出到指定⽬录中。

如何在Java中进行文件的压缩和解压缩

如何在Java中进行文件的压缩和解压缩

如何在Java中进行文件的压缩和解压缩在Java中进行文件的压缩和解压缩是常见的操作,可以使用Java 标准库提供的功能来实现。

本文将介绍如何使用Java中的ZipOutputStream来进行文件压缩,以及使用ZipInputStream来进行文件解压缩。

一、文件的压缩文件的压缩是将一个或多个文件或文件夹打包成一个压缩文件,压缩文件通常使用.zip格式。

在Java中,可以使用ZipOutputStream 来创建一个新的压缩文件,并将文件添加到压缩文件中。

1.创建压缩文件要使用ZipOutputStream创建一个新的压缩文件,首先需要创建一个FileOutputStream来写入文件的数据。

然后将FileOutputStream 传递给ZipOutputStream的构造函数,以创建一个与特定文件关联的ZipOutputStream。

```javaFileOutputStream fos = newFileOutputStream("compressed.zip");ZipOutputStream zos = new ZipOutputStream(fos);```上述代码中,我们创建了一个名为compressed.zip的压缩文件,并将其关联到一个FileOutputStream中。

接下来,我们将使用ZipOutputStream对象向文件中添加数据。

2.向压缩文件中添加文件要向压缩文件中添加一个文件,可以使用ZipEntry和putNextEntry方法。

ZipEntry表示压缩文件中的一个条目,我们可以通过ZipEntry的构造函数来创建一个新的条目,并使用putNextEntry 方法来指定下一个要添加数据的条目。

```javaFile fileToAdd = new File("fileToAdd.txt");ZipEntry zipEntry = new ZipEntry(fileToAdd.getName());zos.putNextEntry(zipEntry);//将fileToAdd的数据写入到压缩文件中FileInputStream fis = new FileInputStream(fileToAdd);byte[] buffer = new byte[1024];int length;while ((length = fis.read(buffer)) > 0) {zos.write(buffer, 0, length);}//关闭当前条目zos.closeEntry();fis.close();```在上述代码中,我们首先创建一个ZipEntry来表示将要添加的文件,然后使用putNextEntry方法指定下一个要添加数据的条目。

使用Java?API压缩和?解压缩数据

使用Java?API压缩和?解压缩数据

使⽤Java?API压缩和?解压缩数据使⽤Java API压缩和解压缩数据(2007-09-24 09:29:52)转载标签:学习公社分类:⼯作参考⽂档从ZIP⽂件解压并抽取数据java.util.zip包提供了数据压缩和解压缩的类。

解压ZIP⽂件实质是从输⼊流中读出数据。

java.util.zip包提供了读取ZIP⽂件的ZipInputStream类。

可以像任何其他输⼊流那样创建ZipInputStream。

例如,下列代码可⽤于创建输FileInputStream fis = new FileInputStream("figs.zip"); ZipInputStream zin = new ZipInputStream(new BufferedInputStream(fis));⼀旦打开ZIP输⼊流,就可以使⽤getNextEntry⽅法读取zip条⽬,该⽅法返回ZipEntry对象。

如果到达⽂件末尾,getNextEntry就会返回零值:ZipEntry entry; while((entry = zin.getNextEntry()) != null) { // extract data // open output streams }现在创建解压缩输出流,如下:int BUFFER = 2048; FileOutputStream fos = new FileOutputStream(entry.getName()); BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER);注意: 在此节代码中,我们⽤BufferedOutputStream代替了ZIPOutputStream。

ZIPOutputStream和GZIPOutputStream使⽤⼤⼩为 512 的内部缓冲。

BufferedOutputStream的使⽤仅在缓冲的⼤⼩远远超过 512 时(本例的设置为在本节代码中,⽂件输出流是使⽤条⽬的名称创建的,该名称可以使⽤entry.getName⽅法进⾏检索。

Java解压和压缩带密码的zip文件过程详解

Java解压和压缩带密码的zip文件过程详解

Java解压和压缩带密码的zip⽂件过程详解前⾔JDK⾃带的ZIP操作接⼝(java.util.zip包,请参看⽂章末尾的博客链接)并不⽀持密码,甚⾄也不⽀持中⽂⽂件名。

为了解决ZIP压缩⽂件的密码问题,在⽹上搜索良久,终于找到了winzipaes开源项⽬。

该项⽬在下托管,仅⽀持AES压缩和解压zip⽂件( This library only supports Win-Zip's 256-Bit AES mode.)。

⽹站上下载的⽂件是源代码,最新版本为winzipaes_src_20120416.zip,本⽰例就是在此基础上编写。

详述项⽬使⽤很简单,利⽤源码⾃⼰导出⼀个jar⽂件,在项⽬中引⽤即可。

这⾥有⼀个需要注意的问题,就是如果给定ZIP⽂件没有密码,那么就不能使⽤该项⽬解压,如果压缩⽂件没有密码却使⽤该项⽬解压在这⾥会报⼀个异常,所以使⽤中需要注意:加密ZIP⽂件可以使⽤它解压,没有加密的就需要采取其它⽅式了。

此⽂就是采⽤修改后的winzipaes编写,并记录详细修改步骤。

⽰例在研究该项⽬时写了⼀个⼯具类,本来准备⽤在项⽬中,最后找到了更好的解决⽅案zip4j来代替,所以最终没有采⽤。

package com.ninemax.demo.zip.decrypt;import java.io.File;import java.io.IOException;import java.util.List;import java.util.zip.DataFormatException;import mons.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, stIndexOf(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⽂件加进来。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

利用Java实现zip压缩/解压缩【青鸟资源分享】由于网络带宽有限,所以数据文件的压缩有利于数据在Internet上的快速传输,同时也节省服务器的外存空间。

java 1.1实现了I/O数据流与网络数据流的单一接口,因此数据的压缩、网络传输和解压缩的实现比较容易,下面介绍利用ZipEntry、ZipInputStream和ZipOutputStream三个Java 类实现zip数据压缩方式的编程方法。

zip压缩文件结构:一个zip文件由多个entry组成,每个entry有一个唯一的名称,entry 的数据项存储压缩数据。

与zip文件有关的几个Java类·类ZipEntrypublic ZipEntry(String name);name为指定的数据项名。

·类ZipOutputStreamZipOutputStream实现了zip压缩文件的写输出流,支持压缩和非压缩entry。

下面是它的几个函数:public ZipOutputStream(OutputStream out);∥利用输出流out构造一个ZIP输出流。

public void setMethod(int method);∥设置entry压缩方法,缺省值为DEFLATED。

public void putNextEntry(ZipEntry newe);∥如果当前的entry存在且处于激活状态时,关闭它,在zip文件中写入新的entry-newe 并将数据流定位于entry数据项的起始位置,压缩方法为setMethod指定的方法。

·类ZipInputStreamZipInputStream实现了zip压缩文件的读输入流,支持压缩和非压缩entry。

下面是它的几个函数:public ZipInputStream(InputStream in);∥利用输入流in构造一个ZIP输出流。

public ZipEntry getNextEntry();∥返回ZIP文件中的下一个entry,并将输出流定位在此entry数据项的起始位置。

public void closeEntry();∥关闭当前的zip entry,并将数据流定位于下一个entry的起始位置。

程序代码及其注释下列的程序实现了数据文件zip方式的压缩和解压缩方法。

randomData()函数随机生成50个double数据,并放在doc字符串变量中;openFile()函数读取ZIP压缩文件;saveFile()函数将随机生成的数据存到ZIP格式的压缩文件中。

1. import java.util.zip.*;2.import java.awt.event.*;3.import java.awt.*;4.import ng.Math;5.import java.io.*;6.public class TestZip extends Frame implements ActionListener {7.TextArea textarea; ∥显示数据文件的多行文本显示域8.TextField infotip; ∥显示数据文件未压缩大小及压缩大小单行文本显示域9.String doc; ∥存储随机生成的数据10.long doczipsize = 0;∥压缩数据文件的大小11.public TestZip(){12.∥生成菜单13.MenuBar menubar = new MenuBar();14.setMenuBar(menubar);15.Menu file = new Menu("File",true);16.menubar.add(file);17.MenuItem neww= new MenuItem("New");18.neww.addActionListener(this);19.file.add(neww);20.MenuItem open=new MenuItem("Open");21.open.addActionListener(this);22.file.add(open);23.MenuItem save=new MenuItem("Save");24.save.addActionListener(this);25.file.add(save);26.MenuItem exit=new MenuItem("Exit");27.exit.addActionListener(this);28.file.add(exit);29.∥随机生成的数据文件的多行文本显示域30.add("Center",textarea = new TextArea());31.∥提示文本原始大小、压缩大小的单行文本显示域32.add("South",infotip = new TextField());33.}34.public static void main(String args[]){35.TestZip ok=new TestZip();36.ok.setTitle("zip sample");37.ok.setSize(600,300);38.ok.show();39.}40.private void randomData(){41.∥随机生成50个double数据,并放在doc字符串变量中。

42.doc="";43.for(int i=1;i<51;i++){44. double rdm=Math.random()*10;45. doc=doc+new Double(rdm).toString();46. if(i%5 == 0) doc=doc+"n";47. else doc=doc+" ";48.}49.doczipsize = 0;50.showTextandInfo();51.}52.private void openFile(){53.∥打开zip文件,将文件内容读入doc字符串变量中。

54.FileDialog dlg=new FileDialog(this,"Open",FileDialog.LOA D);55.dlg.show();56.String filename=dlg.getDirectory()+dlg.getFile();57.try{58.∥创建一个文件实例59.File f=new File(filename);60.if(!f.exists()) return; ∥文件不存在,则返回61.∥用文件输入流构建ZIP压缩输入流62.ZipInputStream zipis=new ZipInputStream(new FileInputStream(f));63.zipis.getNextEntry();64.∥将输入流定位在当前entry数据项位置65.DataInputStream dis=new DataInputStream(zipis);66.∥用ZIP输入流构建DataInputStream67.doc=dis.readUTF();∥读取文件内容68.dis.close();∥关闭文件69.doczipsize = f.length();∥获取ZIP文件长度70.showTextandInfo();∥显示数据71.}72.catch(IOException ioe){73.System.out.println(ioe);74.}75.}76.private void saveFile(){77.∥打开zip文件,将doc字符串变量写入zip文件中。

78.FileDialog dlg=new FileDialog(this,"Save",FileDialog.SAVE);79.dlg.show();80.String filename=dlg.getDirectory()+dlg.getFile();81.try{82.∥创建一个文件实例83.File f=new File(filename);84.if(!f.exists()) return; ∥文件不存在,则返回85.∥用文件输出流构建ZIP压缩输出流86.ZipOutputStream zipos=new ZipOutputStream(new FileOutputStream(f));87.zipos.setMethod(ZipOutputStream.DEFLATED); ∥设置压缩方法88.zipos.putNextEntry(new ZipEntry("zip"));89.∥生成一个ZIP entry,写入文件输出流中,并将输出流定位于entry起始处。

90.DataOutputStream os=new DataOutputStream(zipos);91.∥用ZIP输出流构建DataOutputStream;92.os.writeUTF(doc);∥将随机生成的数据写入文件中93.os.close();∥关闭数据流94.doczipsize = f.length();95.∥获取压缩文件的长度96.showTextandInfo();∥显示数据97.}98.catch(IOException ioe){99.System.out.println(ioe);100.}101.}102.private void showTextandInfo(){103.∥显示数据文件和压缩信息104.textarea.replaceRange(doc,0,textarea.getText().length());tip.setText("uncompressed size: "+doc.length()+"compressed size: "+dc zipsize);106.}107.public void actionPerformed(ActionEvent e){108.String arg = e.getActionCommand();109.if ("New".equals(arg)) randomData();110.else if ("Open".equals(arg)) openFile();111.else if ("Save".equals(arg)) saveFile();112.else if ("Exit".equals(arg)){113. dispose();∥关闭窗口114. System.exit(0);∥关闭程序115.}116.else {117. System.out.println("no this command!");118.}119.}120.}复制代码Java其实很强大、但是我还是比较喜欢Android、、、为什么?因为C#拖控件习惯了、、、。

相关文档
最新文档