java怎样压缩文件夹

java怎样压缩文件夹,第1张

压缩文件夹代码:

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 = 0i <fl.lengthi++) {

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

}

}

}

import java.io.*

import java.util.zip.*

public class CompressD {

// 缓冲

static byte[] buffer = new byte[2048]

public static void main(String[] args) throws Exception {

// 来源

File inputDir = new File("C:\\誉物CompressTest\\")

// 目标

FileOutputStream fos = new FileOutputStream("C:\\CompressTest.zip"亩消)

// 过滤

ZipOutputStream zos = new ZipOutputStream(fos)

//迅虚知 压缩

zip(inputDir.listFiles(), "", zos)

// 关闭

zos.close()

}

private static void zip(File[] files, String baseFolder, ZipOutputStream zos)

throws Exception {

// 输入

FileInputStream fis = null

// 条目

ZipEntry entry = null

// 数目

int count = 0

for (File file : files) {

if (file.isDirectory()) {

// 递归

zip(file.listFiles(), file.getName() + File.separator, zos)

continue

}

entry = new ZipEntry(baseFolder + file.getName())

// 加入

zos.putNextEntry(entry)

fis = new FileInputStream(file)

// 读取

while ((count = fis.read(buffer, 0, buffer.length)) != -1)

// 写入

zos.write(buffer, 0, count)

}

}

}


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/tougao/8154700.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-04-13
下一篇 2023-04-13

发表评论

登录后才能评论

评论列表(0条)

保存