java進行檔案的壓縮(ZIP)
最近需要用到壓縮,然後網上找了一些,自己又改了一些,寫一下吧,希望有用的可以做一個參考
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class ZipWar {
public static void getZipWar(String path,String contextPath) {
File fileFolder = new File(path);
File[] listFiles = fileFolder.listFiles();
String contextPathb = contextPath.substring(1, contextPath.length());
try(ZipOutputStream zipOutputStream = new ZipOutputStream(new FileOutputStream("D:\\"+contextPathb+".zip"))) {
for (File file : listFiles) {
getZipOutPutStreamEntryFile(zipOutputStream,file,contextPathb);
}
} catch (Exception e) {
e.printStackTrace();
}
}
private static void getZipOutPutStreamEntryFile(ZipOutputStream zipOutputStream, File file,String contextPath) throws Exception {
if (file.isDirectory()) {
File[] listFiles = file.listFiles();
for (File file2 : listFiles) {
getZipOutPutStreamEntryFile(zipOutputStream, file2,contextPath);
}
} else {
try {
String path = file.getPath();
//和TarOutputStream的TarEntry放的是File型別,這裡放的是檔名
String[] split = path.split(contextPath);
ZipEntry zipEntry = new ZipEntry(path.substring(path.length()-split[2].length(), path.length()));
zipOutputStream.putNextEntry(zipEntry);
FileInputStream fileInputStream = new FileInputStream(file.getPath());
byte[] b = new byte[1024*1024*5];
int length = 0;
while ((length = fileInputStream.read(b)) != -1) {
zipOutputStream.write(b, 0, length);
}
fileInputStream.close();
zipOutputStream.closeEntry();
//呼叫了這個方法之後,後面的檔案是不能被新增的,壓縮包裡面只有第一個檔案,
// gzipOutputStream.finish();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
==============================================================================================
呼叫:
String path = rootPath+"/WEB-INF/resource/file/"+attribute.getDomain_name();
String contextPathb = req.getContextPath().substring(1, req.getContextPath().length());
/*ZipWar.getZipWar(path,contextPathb);*/
WarZip.zip(path,contextPathb);