zip壓縮流轉本地文件及解壓

有一個需求,HTTP獲取到zip文件的byte數組,需要轉爲本地的zip或是解壓zip文件。


1. 用到的class

import java.io.FileOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
import java.io.ByteArrayInputStream;

2 獲取解壓後的文件

private static void getTxtFile(byte[] data) throws Exception {
		ZipInputStream zipStream = new ZipInputStream(new ByteArrayInputStream(data));
		ZipEntry entry = null;
		while ((entry = zipStream.getNextEntry()) != null) {

			String entryName = entry.getName();

			FileOutputStream out = new FileOutputStream("/log/111/" + entryName);

			byte[] byteBuff = new byte[4096];
			int bytesRead = 0;
			while ((bytesRead = zipStream.read(byteBuff)) != -1) {
				out.write(byteBuff, 0, bytesRead);
			}

			out.close();
			zipStream.closeEntry();
		}
		zipStream.close();
}

3. 轉存zip文件,(可修改zip內的文件名)

private static void getZipFile(byte[] data) throws Exception {
		String filename = "/log/111/111.zip";
		FileOutputStream fileOutputStream = new FileOutputStream(filename);
		ZipOutputStream zos = new ZipOutputStream(fileOutputStream);

		ZipInputStream zipStream = new ZipInputStream(new ByteArrayInputStream(data));
		ZipEntry entry;
		while ((entry = zipStream.getNextEntry()) != null) {
			ZipEntry entry1 = new ZipEntry(entry.getName());
			zos.putNextEntry(entry1);
			zipStream.closeEntry();
		}
		zos.write(data);
		zos.flush();
		zos.closeEntry();
		zos.close();
		zipStream.close();
}

或者簡單粗暴的直接將其保存到本地文件

private static void getZipFile(byte[] data) throws Exception {
		String filename = "/log/111/111.zip";
		File targetFile = new File(filename);
		OutputStream outStream = new FileOutputStream(targetFile);
		outStream.write(data);
		outStream.flush();
		outStream.close();
}




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章