天天看點

JAVA壓縮檔案夾包括裡面的檔案,可以設定壓縮後的目錄結構

package test.downloadzip;

import java.io.File;

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.InputStream;

import java.util.TreeSet;

import java.util.zip.ZipEntry;

import java.util.zip.ZipOutputStream;

public class ZipDemo {

public static TreeSet<String> ts = new TreeSet<String>();

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

// 需要壓縮的目錄

File sFolder = new File("D:\\leo\\file\\pic");

// 壓縮之後的目錄,如果是網絡下載下傳情況可以将流寫入response就好了

File zipFolder = new File("d:\\zipDown\\test.zip");

ZipFolderMethod(sFolder, zipFolder);

System.out.println("導出成功");

}

public static void ZipFolderMethod(File sFoder, File zipFolder) throws IOException {

// TODO Auto-generated method stub

ZipOutputStream zipoutFolder = new ZipOutputStream(new FileOutputStream(zipFolder));

InputStream in = null;

// zipoutFolder.setEncoding("GBK"); //為解決注釋亂碼

zipoutFolder.setComment("檔案夾的壓縮");

// 列出所有檔案的路徑,儲存到集合中,在ListAllDirectory(sFoder)方法中用到遞歸

TreeSet<String> pathTreeSet = ListAllDirectory(sFoder);

String[] pathStr = pathTreeSet.toString().substring(1, pathTreeSet.toString().length() - 1).split(",");

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

String filePath = pathStr[i].trim();

StringBuffer pathURL = new StringBuffer();

String[] tempStr = filePath.split("\\\\"); // 這個地方需要注意,在Java中需要“\\\\”表示“\”字元串。

// 這裡的變量j是從第幾層開始打壓縮包

for (int j = 6; j < tempStr.length - 1; j++) {

pathURL.append(tempStr[j] + File.separator);

}

String path = pathURL.append(tempStr[tempStr.length - 1]).toString();

in = new FileInputStream(new File(filePath));

zipoutFolder.putNextEntry(new ZipEntry(path));

int temp = 0;

while ((temp = in.read()) != -1) {

zipoutFolder.write(temp);

}

in.close();

}

zipoutFolder.close();

}

public static TreeSet<String> ListAllDirectory(File sFolder) {

if (sFolder != null) {

if (sFolder.isDirectory()) {

File f[] = sFolder.listFiles();

if (f != null) {

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

ListAllDirectory(f[i]);

}

}

} else {

ts.add(sFolder.toString());

}

}

return ts;

}

}