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

java压缩文件夹|如何使用java压缩文件夹成为zip包(最简单的的第1张示图

① java压缩文件的问题

如果只从你给的代码来看的话file.getName()这个方法就是来自最开头地方引入的文件import java.util.zip.ZipEntry ; zipOut.setComment("www.mldnjava.cn") ; // 设置注释压缩包里有个注释功能,就相当于备注一样,你在压缩一个包的过程中,你可以选择给它写点什么东西,以方便你根据注释想到里面的大概内容。

② java怎么实现遍历文件夹并压缩的功能

不考虑一个文件夹下有另外一个文件夹的情况下,代码如下

publicstaticvoidZipFolder(Filedirectory)throwsException{FileOutputStreamfout=newFileOutputStream("输出压缩文件test.zip的位置");ZipOutputStreamzout=newZipOutputStream(fout);for(Filefile:directory.listFiles()){byte[]buffer=Files.readAllBytes(file.toPath());ZipEntryzipEntry=newZipEntry(file.getName());zout.putNextEntry(zipEntry);zout.write(buffer);zout.closeEntry();}zout.flush();zout.close();}

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

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

④ 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");}}

⑤ 如何使用java压缩文件夹成为zip包

在JDK中有一个zip工具类:

java.util.zip Provides classes for reading and writing the standard ZIP and GZIP file formats.

使用此类可以将文件夹或者多个文件进行打包压缩操作。

在使用之前先了解关键方法:

ZipEntry(String name) Creates a new zip entry with the specified name.

使用ZipEntry的构造方法可以创建一个zip压缩文件包的实例,然后通过ZipOutputStream将待压缩的文件以流的形式写进该压缩包中。具体实现代码如下:

importjava.io.BufferedInputStream;importjava.io.BufferedOutputStream;importjava.io.File;importjava.io.FileInputStream;importjava.io.FileNotFoundException;importjava.io.FileOutputStream;importjava.io.IOException;importjava.util.zip.ZipEntry;importjava.util.zip.ZipOutputStream;/***将文件夹下面的文件*打包成zip压缩文件**@authoradmin**/publicfinalclassFileToZip{privateFileToZip(){}/***将存放在sourceFilePath目录下的源文件,打包成fileName名称的zip文件,并存放到zipFilePath路径下*@paramsourceFilePath:待压缩的文件路径*@paramzipFilePath:压缩后存放路径*@paramfileName:压缩后文件的名称*@return*/publicstaticbooleanfileToZip(StringsourceFilePath,StringzipFilePath,StringfileName){booleanflag=false;FilesourceFile=newFile(sourceFilePath);FileInputStreamfis=null;BufferedInputStreambis=null;FileOutputStreamfos=null;ZipOutputStreamzos=null;if(sourceFile.exists()==false){System.out.println("待压缩的文件目录:"+sourceFilePath+"不存在.");}else{try{FilezipFile=newFile(zipFilePath+"/"+fileName+".zip");if(zipFile.exists()){System.out.println(zipFilePath+"目录下存在名字为:"+fileName+".zip"+"打包文件.");}else{File[]sourceFiles=sourceFile.listFiles();if(null==sourceFiles||sourceFiles.length<1){System.out.println("待压缩的文件目录:"+sourceFilePath+"里面不存在文件,无需压缩.");}else{fos=newFileOutputStream(zipFile);zos=newZipOutputStream(newBufferedOutputStream(fos));byte[]bufs=newbyte[1024*10];for(inti=0;i<sourceFiles.length;i++){//创建ZIP实体,并添加进压缩包ZipEntryzipEntry=newZipEntry(sourceFiles[i].getName());zos.putNextEntry(zipEntry);//读取待压缩的文件并写进压缩包里fis=newFileInputStream(sourceFiles[i]);bis=newBufferedInputStream(fis,1024*10);intread=0;while((read=bis.read(bufs,0,1024*10))!=-1){zos.write(bufs,0,read);}}flag=true;}}}catch(FileNotFoundExceptione){e.printStackTrace();thrownewRuntimeException(e);}catch(IOExceptione){e.printStackTrace();thrownewRuntimeException(e);}finally{//关闭流try{if(null!=bis)bis.close();if(null!=zos)zos.close();}catch(IOExceptione){e.printStackTrace();thrownewRuntimeException(e);}}}returnflag;}publicstaticvoidmain(String[]args){StringsourceFilePath="D:\TestFile";StringzipFilePath="D:\tmp";StringfileName="12700153file";booleanflag=FileToZip.fileToZip(sourceFilePath,zipFilePath,fileName);if(flag){System.out.println("文件打包成功!");}else{System.out.println("文件打包失败!");}}}

⑥ 怎样用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();}}}

⑦ java 如何压缩文件

楼主是说解压了来的文件大小只源有33.1MB,但是却占了51.2MB的空间吗?如果是这个意思的话,那我要告诉楼主,首先这个问题和JAVA没有关系,根据你的截图,可以断定你用的是FAT32文件系统。这只是文件存储的形式,很正常。简单的说,磁盘存储数据的最小单位是簇,比方说你的簇大小为128K,一个簇只能存放一个文件,然后你的一个文件只有16K,它占了这个簇,然后还有112K没有用,是吧。但是那112K就不能再存放其它文件了。如果要存放其它文件,就要占另一个簇。楼主,懂了吧,这跟簇的大小有关,但是也不是簇越小越好,簇越小,读写性能都有所下降。这是正常现象。如果你非觉得不舒服,那就用NTFS文件系统吧,把压缩打开,就不会有这种情况了,希望对你有帮助

⑧ 如何使用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 版本问题*/

⑨ java 怎么把文件压缩

用Eclipse可以将java文件打成.jar包,再用exe4打成exe文件,不过exe4貌似不是免费的,打成jar包的具体过程是File->Export->java->jar file->next->选择工程中的java文件->下面选择jar包的路径->next->main class礼选择主类->finish,就ok 了,注意,只有你的机子上安装了jre/jdk之后打出来的才是jar包,直接点击才能运行,不然打出来的是压缩包,也就是说jar包只有在装了java运行环境的机子上才可以运行

⑩ java怎样压缩文件夹

压缩文件夹代码:import java.io.File;import org.apache.tools.zip.ZipOutputStream; //这个包在ant.jar里,要到官方网下载import java.io.FileInputStream;import java.io.FileOutputStream;import java.util.zip.ZipInputStream;import java.util.zip.ZipEntry;public class CompressBook { public CompressBook() {} /* * inputFileName 输入一个文件夹 * zipFileName 输出一个压缩文件夹 */ public void zip(String inputFileName) throws Exception { String zipFileName = "c:\\test.zip"; //打包后文件名字 System.out.println(zipFileName); zip(zipFileName, new File(inputFileName)); } private void zip(String zipFileName, File inputFile) throws Exception { ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFileName)); zip(out, inputFile, ""); System.out.println("zip done"); out.close(); } private void zip(ZipOutputStream out, File f, String base) throws Exception { if (f.isDirectory()) { File[] fl = f.listFiles(); out.putNextEntry(new org.apache.tools.zip.ZipEntry(base + "/")); base = base.length() == 0 ? "" : base + "/"; for (int i = 0; i < fl.length; i++) { zip(out, fl[i], base + fl[i].getName()); } }else { out.putNextEntry(new org.apache.tools.zip.ZipEntry(base)); FileInputStream in = new FileInputStream(f); int b; System.out.println(base); while ( (b = in.read()) != -1) { out.write(b); } in.close(); } } public static void main(String [] temp){ CompressBook book = new CompressBook(); try { book.zip("c:\\c");//你要压缩的文件夹 }catch (Exception ex) { ex.printStackTrace(); } }}

未经允许不得转载:山九号 » java压缩文件夹|如何使用java压缩文件夹成为zip包(最简单的

赞 (0)