导航:首页 > 文件处理 > javazip压缩

javazip压缩

发布时间:2022-01-30 03:34:45

java中zip压缩文件最多能压缩多少

这个没有固定比例的,取决于被压缩的内容,极端情况下甚至比原始数据还要大

㈡ java zip压缩工具类有哪些

import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import org.apache.tools.zip.ZipEntry; import org.apache.tools.zip.ZipOutputStream; /** * @project: Test

㈢ java中zip压缩输入输出流的问题,ZipEntry()方法里的参数到底什么意思

ZipEntry 用于保存一些被压缩文件的信息,如文件名,最后访问时间,最后修改时间,创建时间,文件大小,crc 校验值 等信息。

ZipEntry 具有一个带 String 类型参数的构造方法:ZipEntry(String name), name 是入口名称,就是打开压缩文件时,看到的里面的文件名称。

可以看一下它的源码,下面是部分源码:

public
,Cloneable{

Stringname;//entryname
longtime=-1;//lastmodificationtime
FileTimemtime;//lastmodificationtime,fromextrafielddata
FileTimeatime;//lastaccesstime,fromextrafielddata
FileTimectime;//creationtime,fromextrafielddata
longcrc=-1;//crc-32ofentrydata
longsize=-1;//uncompressedsizeofentrydata
longcsize=-1;//compressedsizeofentrydata
intmethod=-1;//compressionmethod
intflag=0;//generalpurposeflag
byte[]extra;//
Stringcomment;//optionalcommentstringforentry

...
}

㈣ 如何使用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 如何将 txt 文件 变成zip压缩文件 求例子!!

这个要用 压缩流类 ZipOutputStream
下面是一个例子 在D盘下有个 名字叫 demo.txt的文件.程序运行后会再D盘下生成一个demo.zip的文件,以下是代码:
import java.io.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class ZipOutputStreamDemo {
public static void main(String args[]) throws IOException {
//定义要压缩的文件 也就是说在D盘里有个 demo.txt 的文件(必须要有,否者会有异常,实际应用中可判断);
File file = new File("d:" + File.separator + "demo.txt");

//定义压缩文件的名称
File zipFile = new File("d:" + File.separator + "demo.zip");

//定义输入文件流
InputStream input = new FileInputStream(file);

//定义压缩输出流
ZipOutputStream zipOut = null;

//实例化压缩输出流,并制定压缩文件的输出路径 就是D盘下,名字叫 demo.zip
zipOut = new ZipOutputStream(new FileOutputStream(zipFile));

zipOut.putNextEntry(new ZipEntry(file.getName()));

//设置注释
zipOut.setComment("www.demo.com");
int temp = 0;
while((temp = input.read()) != -1) {
zipOut.write(temp);
}
input.close();
zipOut.close();

}
}
希望能帮助楼主,建议楼主多看看JDK文档,设计到文件的输出什么都在JAVA.IO包里,好好看看..
不过楼主要知道,压缩流也是inputstream和outputstream的子类,但是并没有定义在java.io包里,而是以一个工具类的形式出现的,但是在用的时候还是需要java.io包的支持的...

㈥ 如何使用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怎么实现zip分卷压缩有关问题

直接用java 调用wondows 的cmd 就行了, 至于这个具体的命令 是7-zip提供的,这个需要去看看7-zip的文档.

㈧ java中zip压缩和gzip压缩的区别

一个zip可以内藏多个文件
狭义的gzip仅对单个文件压缩,不能打包多个文件。
tar.gzip或tgz可以打包多个文件,属于固实压缩,压缩比较高,但随机存取单个文件的效率不如zip..

㈨ 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文件的压缩解压

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();
}
}
}

阅读全文

与javazip压缩相关的资料

热点内容
程序员做多久才有前途 浏览:268
工程量换算法楼梯顶棚 浏览:514
倩女幽魂分手为什么没服务器 浏览:201
mvr压缩机开启条件 浏览:788
ras共享文件夹 浏览:235
图论经典算法 浏览:818
室内定位常用算法 浏览:794
正整数除小数算法 浏览:797
程序员柠檬看网 浏览:357
程序员陆漓怀孕真相 浏览:416
xp系统如何配置支持服务器身份验证 浏览:772
蜜熊app聊天怎么样 浏览:307
杨命令 浏览:844
夏天解压球图片大全 浏览:852
怎么将程序安装在服务器里 浏览:754
python删除temp 浏览:603
快手怎么传长视频安卓 浏览:226
阿里云网络服务器架构 浏览:769
VIX算法本质 浏览:192
python蒙特卡洛模拟任务网络计划 浏览:169