怎样用Java生成ZIP文件

Python040

怎样用Java生成ZIP文件,第1张

写了一个 楼主试试吧

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 TestZip {

public static void main(String[] args) {

String srcFilePath = "f:/sql.txt"

String zipFilePath = "f:/outfile.zip"

zipFile(srcFilePath, zipFilePath)

}

/**

* 压缩文件

* @param srcFilePath 需要压缩的文件的完整路径

* @param zipFilePath 压缩生成的文件的路径

* */

private static void zipFile(String srcFilePath, String zipFilePath) {

if(srcFilePath == null){

throw new RuntimeException("需要压缩的文件的完整路径 不能为空!")

}

if(zipFilePath == null){

throw new RuntimeException("压缩生成的文件的路径 不能为空!")

}

ZipOutputStream zout = null

FileInputStream fin = null

try{

File txtFile = new File(srcFilePath)

fin = new FileInputStream(txtFile)

}catch (FileNotFoundException e) {

throw new RuntimeException("压缩失败!找不到文件" + srcFilePath)

}finally {

try {

fin.close()

} catch (Exception e) {

}

}

try {

zout = new ZipOutputStream(new FileOutputStream(new File(zipFilePath)))

File srcFile = new File(srcFilePath)

fin = new FileInputStream(srcFile)

byte[] bb = new byte[4096]

int i = 0

zout.putNextEntry(new ZipEntry(srcFile.getName()))

while ((i = fin.read(bb)) != -1) {

zout.setLevel(9)

zout.write(bb, 0, i)

}

} catch (IOException e) {

throw new RuntimeException("压缩失败!", e)

} finally {

try {

zout.close()

fin.close()

} catch (Exception e) {

}

}

}

}

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 版本问题*/