资讯

精准传达 • 有效沟通

从品牌网站建设到网络营销策划,从策略到执行的一站式服务

java源代码文件压缩 源代码怎么压缩

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

package zip;

为尚义等地区用户提供了全套网页设计制作服务,及尚义网站建设行业解决方案。主营业务为成都网站制作、做网站、外贸营销网站建设、尚义网站设计,以传统方式定制建设网站,并提供域名空间备案等一条龙服务,秉承以专业、用心的态度为用户提供真诚的服务。我们深信只要达到每一位用户的要求,就会得到认可,从而选择与我们长期合作。这样,我们也可以走得更远!

import java.io.BufferedInputStream;

import java.io.BufferedOutputStream;

import java.io.File;

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.util.Enumeration;

import java.util.zip.CRC32;

import java.util.zip.CheckedOutputStream;

import java.util.zip.ZipEntry;

import java.util.zip.ZipFile;

import java.util.zip.ZipOutputStream;

import org.apache.commons.lang3.StringUtils;

public class ZipUtil {

/**

 * 递归压缩文件夹

 * @param srcRootDir 压缩文件夹根目录的子路径

 * @param file 当前递归压缩的文件或目录对象

 * @param zos 压缩文件存储对象

 * @throws Exception

 */

private static void zip(String srcRootDir, File file, ZipOutputStream zos) throws Exception

{

if (file == null) 

{

return;

}

//如果是文件,则直接压缩该文件

if (file.isFile())

{

int count, bufferLen = 1024;

byte data[] = new byte[bufferLen];

//获取文件相对于压缩文件夹根目录的子路径

String subPath = file.getAbsolutePath();

int index = subPath.indexOf(srcRootDir);

if (index != -1) 

{

subPath = subPath.substring(srcRootDir.length() + File.separator.length());

}

ZipEntry entry = new ZipEntry(subPath);

zos.putNextEntry(entry);

BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));

while ((count = bis.read(data, 0, bufferLen)) != -1) 

{

zos.write(data, 0, count);

}

bis.close();

zos.closeEntry();

}

//如果是目录,则压缩整个目录

else 

{

//压缩目录中的文件或子目录

File[] childFileList = file.listFiles();

for (int n=0; nchildFileList.length; n++)

{

childFileList[n].getAbsolutePath().indexOf(file.getAbsolutePath());

zip(srcRootDir, childFileList[n], zos);

}

}

}

/**

 * 对文件或文件目录进行压缩

 * @param srcPath 要压缩的源文件路径。如果压缩一个文件,则为该文件的全路径;如果压缩一个目录,则为该目录的顶层目录路径

 * @param zipPath 压缩文件保存的路径。注意:zipPath不能是srcPath路径下的子文件夹

 * @param zipFileName 压缩文件名

 * @throws Exception

 */

public static void zip(String srcPath, String zipPath, String zipFileName) throws Exception

{

if (StringUtils.isEmpty(srcPath) || StringUtils.isEmpty(zipPath) || StringUtils.isEmpty(zipFileName))

{

throw new ParameterException(ICommonResultCode.PARAMETER_IS_NULL);

}

CheckedOutputStream cos = null;

ZipOutputStream zos = null;

try

{

File srcFile = new File(srcPath);

//判断压缩文件保存的路径是否为源文件路径的子文件夹,如果是,则抛出异常(防止无限递归压缩的发生)

if (srcFile.isDirectory()  zipPath.indexOf(srcPath)!=-1) 

{

throw new ParameterException(ICommonResultCode.INVALID_PARAMETER, "zipPath must not be the child directory of srcPath.");

}

//判断压缩文件保存的路径是否存在,如果不存在,则创建目录

File zipDir = new File(zipPath);

if (!zipDir.exists() || !zipDir.isDirectory())

{

zipDir.mkdirs();

}

//创建压缩文件保存的文件对象

String zipFilePath = zipPath + File.separator + zipFileName;

File zipFile = new File(zipFilePath);

if (zipFile.exists())

{

//检测文件是否允许删除,如果不允许删除,将会抛出SecurityException

SecurityManager securityManager = new SecurityManager();

securityManager.checkDelete(zipFilePath);

//删除已存在的目标文件

zipFile.delete();

}

cos = new CheckedOutputStream(new FileOutputStream(zipFile), new CRC32());

zos = new ZipOutputStream(cos);

//如果只是压缩一个文件,则需要截取该文件的父目录

String srcRootDir = srcPath;

if (srcFile.isFile())

{

int index = srcPath.lastIndexOf(File.separator);

if (index != -1)

{

srcRootDir = srcPath.substring(0, index);

}

}

//调用递归压缩方法进行目录或文件压缩

zip(srcRootDir, srcFile, zos);

zos.flush();

}

catch (Exception e) 

{

throw e;

}

finally 

{

try

{

if (zos != null)

{

zos.close();

}

}

catch (Exception e)

{

e.printStackTrace();

}

}

}

/**

 * 解压缩zip包

 * @param zipFilePath zip文件的全路径

 * @param unzipFilePath 解压后的文件保存的路径

 * @param includeZipFileName 解压后的文件保存的路径是否包含压缩文件的文件名。true-包含;false-不包含

 */

@SuppressWarnings("unchecked")

public static void unzip(String zipFilePath, String unzipFilePath, boolean includeZipFileName) throws Exception

{

if (StringUtils.isEmpty(zipFilePath) || StringUtils.isEmpty(unzipFilePath))

{

throw new ParameterException(ICommonResultCode.PARAMETER_IS_NULL);

}

File zipFile = new File(zipFilePath);

//如果解压后的文件保存路径包含压缩文件的文件名,则追加该文件名到解压路径

if (includeZipFileName)

{

String fileName = zipFile.getName();

if (StringUtils.isNotEmpty(fileName))

{

fileName = fileName.substring(0, fileName.lastIndexOf("."));

}

unzipFilePath = unzipFilePath + File.separator + fileName;

}

//创建解压缩文件保存的路径

File unzipFileDir = new File(unzipFilePath);

if (!unzipFileDir.exists() || !unzipFileDir.isDirectory())

{

unzipFileDir.mkdirs();

}

//开始解压

ZipEntry entry = null;

String entryFilePath = null, entryDirPath = null;

File entryFile = null, entryDir = null;

int index = 0, count = 0, bufferSize = 1024;

byte[] buffer = new byte[bufferSize];

BufferedInputStream bis = null;

BufferedOutputStream bos = null;

ZipFile zip = new ZipFile(zipFile);

EnumerationZipEntry entries = (EnumerationZipEntry)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 = new File(entryDirPath);

//如果文件夹路径不存在,则创建文件夹

if (!entryDir.exists() || !entryDir.isDirectory())

{

entryDir.mkdirs();

}

//创建解压文件

entryFile = new File(entryFilePath);

if (entryFile.exists())

{

//检测文件是否允许删除,如果不允许删除,将会抛出SecurityException

SecurityManager securityManager = new SecurityManager();

securityManager.checkDelete(entryFilePath);

//删除已存在的目标文件

entryFile.delete();

}

//写入文件

bos = new BufferedOutputStream(new FileOutputStream(entryFile));

bis = new BufferedInputStream(zip.getInputStream(entry));

while ((count = bis.read(buffer, 0, bufferSize)) != -1)

{

bos.write(buffer, 0, count);

}

bos.flush();

bos.close();

}

}

public static void main(String[] args) 

{

String zipPath = "d:\\ziptest\\zipPath";

String dir = "d:\\ziptest\\rawfiles";

String zipFileName = "test.zip";

try

{

zip(dir, zipPath, zipFileName);

catch (Exception e)

{

e.printStackTrace();

}

String zipFilePath = "D:\\ziptest\\zipPath\\test.zip";

String unzipFilePath = "D:\\ziptest\\zipPath";

try 

{

unzip(zipFilePath, unzipFilePath, true);

}

catch (Exception e)

{

e.printStackTrace();

}

}

}

如何使用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将待压缩的文件以流的形式写进该压缩包中。具体实现代码如下:

import java.io.BufferedInputStream;  

import java.io.BufferedOutputStream;  

import java.io.File;  

import java.io.FileInputStream;  

import java.io.FileNotFoundException;  

import java.io.FileOutputStream;  

import java.io.IOException;  

import java.util.zip.ZipEntry;  

import java.util.zip.ZipOutputStream;  

/** 

* 将文件夹下面的文件 

* 打包成zip压缩文件 

*  

* @author admin 

*/  

public final class FileToZip {  

private FileToZip(){}  

/** 

* 将存放在sourceFilePath目录下的源文件,打包成fileName名称的zip文件,并存放到zipFilePath路径下 

* @param sourceFilePath :待压缩的文件路径 

* @param zipFilePath :压缩后存放路径 

* @param fileName :压缩后文件的名称 

* @return 

*/  

public static boolean fileToZip(String sourceFilePath,String zipFilePath,String fileName){  

boolean flag = false;  

File sourceFile = new File(sourceFilePath);  

FileInputStream fis = null;  

BufferedInputStream bis = null;  

FileOutputStream fos = null;  

ZipOutputStream zos = null;  

if(sourceFile.exists() == false){  

System.out.println("待压缩的文件目录:"+sourceFilePath+"不存在.");  

}else{  

try {  

File zipFile = new File(zipFilePath + "/" + fileName +".zip");  

if(zipFile.exists()){  

System.out.println(zipFilePath + "目录下存在名字为:" + fileName +".zip" +"打包文件.");  

}else{  

File[] sourceFiles = sourceFile.listFiles();  

if(null == sourceFiles || sourceFiles.length1){  

System.out.println("待压缩的文件目录:" + sourceFilePath + "里面不存在文件,无需压缩.");  

}else{  

fos = new FileOutputStream(zipFile);  

zos = new ZipOutputStream(new BufferedOutputStream(fos));  

byte[] bufs = new byte[1024*10];  

for(int i=0;isourceFiles.length;i++){  

//创建ZIP实体,并添加进压缩包  

ZipEntry zipEntry = new ZipEntry(sourceFiles[i].getName());  

zos.putNextEntry(zipEntry);  

//读取待压缩的文件并写进压缩包里  

fis = new FileInputStream(sourceFiles[i]);  

bis = new BufferedInputStream(fis, 1024*10);  

int read = 0;  

while((read=bis.read(bufs, 0, 1024*10)) != -1){  

zos.write(bufs,0,read);  

}  

}  

flag = true;  

}  

}  

} catch (FileNotFoundException e) {  

e.printStackTrace();  

throw new RuntimeException(e);  

} catch (IOException e) {  

e.printStackTrace();  

throw new RuntimeException(e);  

} finally{  

//关闭流  

try {  

if(null != bis) bis.close();  

if(null != zos) zos.close();  

} catch (IOException e) {  

e.printStackTrace();  

throw new RuntimeException(e);  

}  

}  

}  

return flag;  

}  

public static void main(String[] args){  

String sourceFilePath = "D:\\TestFile";  

String zipFilePath = "D:\\tmp";  

String fileName = "12700153file";  

boolean flag = FileToZip.fileToZip(sourceFilePath, zipFilePath, fileName);  

if(flag){  

System.out.println("文件打包成功!");  

}else{  

System.out.println("文件打包失败!");  

}  

}  

}

求JAVA解压缩文件目录的源代码

package com.io2.homework;

import java.io.File;

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.FileOutputStream;

import java.io.IOException;

import java.util.zip.ZipEntry;

import java.util.zip.ZipOutputStream;

/*压缩文件夹*/

public class MyMultipleFileZip 

{

private String currentZipFilePath = "F:/MyZip.zip";

private String sourceFilePath;

private ZipOutputStream zos;

private FileInputStream fis;

public MyMultipleFileZip(String sourceFilePath) 

{

try

{

this.sourceFilePath = sourceFilePath;

zos = new ZipOutputStream(new FileOutputStream(currentZipFilePath));

//设定文件压缩级别

zos.setLevel(9);

} catch (FileNotFoundException e) 

{

e.printStackTrace();

}

}

// 在当前条目中写入具体内容

public void writeToEntryZip(String filePath) 

{

try

{

fis = new FileInputStream(filePath);

} catch (FileNotFoundException e1) 

{

e1.printStackTrace();

}

byte[] buff = new byte[1024];

int len = 0;

try 

{

while ((len = fis.read(buff)) != -1)

{

zos.write(buff, 0, len);

}

} catch (IOException e) 

{

e.printStackTrace();

}finally

{

if (fis != null)

try 

{

fis.close();

} catch (IOException e) 

{

e.printStackTrace();

}

}

}

// 添加文件条目

public void addFileEntryZip(String fileName) 

{

try 

{

zos.putNextEntry(new ZipEntry(fileName));

} catch (IOException e) 

{

e.printStackTrace();

}

}

public void addDirectoryEntryZip(String directoryName)

{

try 

{

zos.putNextEntry(new ZipEntry(directoryName + "/"));

} catch (IOException e)

{

e.printStackTrace();

}

}

// 遍历文件夹

public void listMyDirectory(String filePath)

{

File f = new File(filePath);

File[] files = f.listFiles();

if(files!=null)

{

for (File currentFile : files) 

{

// 设置条目名称(此步骤非常关键)

String entryName= currentFile.getAbsolutePath().split(":")[1].substring(1);

// 获取文件物理路径

String absolutePath = currentFile.getAbsolutePath();

if (currentFile.isDirectory()) 

{

addDirectoryEntryZip(entryName);

//进行递归调用

listMyDirectory(absolutePath);

}

else 

{

addFileEntryZip(entryName);

writeToEntryZip(absolutePath);

}

}

}

}

// 主要流程

public void mainWorkFlow()

{

listMyDirectory(this.sourceFilePath);

if(zos!=null)

try 

{

zos.close();

} catch (IOException e) 

{

e.printStackTrace();

}

}

public static void main(String[] args) 

{

new MyMultipleFileZip("F:/fountainDirectory").mainWorkFlow();

}

}

怎么把java源代码变成附件文件

通过jar命令

jar命令的用法:

下面是jar命令的帮助说明:

用法:jar {ctxui}[vfm0Me] [jar-file] [manifest-file] [entry-point] [-C dir] files ...

选项包括:

-c 创建新的归档文件

-t 列出归档目录

-x 解压缩已归档的指定(或所有)文件

-u 更新现有的归档文件

-v 在标准输出中生成详细输出

-f 指定归档文件名

-m 包含指定清单文件中的清单信息

-e 为捆绑到可执行 jar 文件的独立应用程序,指定应用程序入口点

-0 仅存储;不使用任何 ZIP 压缩

-M 不创建条目的清单文件

-i 为指定的 jar 文件生成索引信息

-C 更改为指定的目录并包含其中的文件

如果有任何目录文件,则对其进行递归处理。清单文件名、归档文件名和入口点名的指定顺序与 "m"、"f" 和 "e" 标志的指定顺序相同。


当前名称:java源代码文件压缩 源代码怎么压缩
文章路径:http://cdkjz.cn/article/hpspci.html
多年建站经验

多一份参考,总有益处

联系快上网,免费获得专属《策划方案》及报价

咨询相关问题或预约面谈,可以通过以下方式与我们联系

业务热线:400-028-6601 / 大客户专线   成都:13518219792   座机:028-86922220