java文件压缩并下载
- 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 {
- private void zip(String souceFileName, String destFileName) {
- File file = new File(souceFileName);
- try {
- zip(file, destFileName);
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- private void zip(File souceFile, String destFileName) throws IOException {
- FileOutputStream fileOut = null;
- try {
- fileOut = new FileOutputStream(destFileName);
- } catch (FileNotFoundException e) {
- e.printStackTrace();
- }
- ZipOutputStream out = new ZipOutputStream(fileOut);
- zip(souceFile, out, "");
- out.close();
- }
- private void zip(File souceFile, ZipOutputStream out, String base)
- throws IOException {
- if (souceFile.isDirectory()) {
- File[] files = souceFile.listFiles();
- out.putNextEntry(new ZipEntry(base + "/"));
- base = base.length() == 0 ? "" : base + "/";
- for (File file : files) {
- zip(file, out, base + file.getName());
- }
- } else {
- if (base.length() > 0) {
- out.putNextEntry(new ZipEntry(base));
- } else {
- out.putNextEntry(new ZipEntry(souceFile.getName()));
- }
- System.out.println("filepath=" + souceFile.getPath());
- FileInputStream in = new FileInputStream(souceFile);
- int b;
- byte[] by = new byte[1024];
- while ((b = in.read(by)) != -1) {
- out.write(by, 0, b);
- }
- in.close();
- }
- }
- /**
- * Test
- */
- public static void main(String[] args) {
- TestZip z = new TestZip();
- z.zip("D:\\image11", "D:/Data1.zip");
- }
- }
/其中
z.zip("D:\\image11", "D:/Data1.zip");
第一个参数是标识要生成目录的文件夹这个会遍历下面所有的文件夹中的文件
第二个参数 生成的zip的文件位置