1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115
|
import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.nio.file.Files; import java.nio.file.Paths; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import java.util.zip.ZipOutputStream;
public class zipTest {
private static void zipFile(FileInputStream inputStream, ZipOutputStream outputStream, String fileName) throws Exception { outputStream.putNextEntry(new ZipEntry(fileName)); try (BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream, 512)) { int index; byte[] buffer = new byte[512]; while ((index = bufferedInputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, index); } } outputStream.closeEntry(); }
public static void createParentPath(File file) { File parentFile = file.getParentFile(); if (null != parentFile && !parentFile.exists()) { parentFile.mkdirs(); createParentPath(parentFile); } }
public static void decompressionFile(String fromZip, String toPath) throws Exception { File baseFile = new File(toPath); if (baseFile.exists()) { baseFile.delete(); } File zipFile = new File(fromZip); ZipInputStream inputStream = new ZipInputStream(new BufferedInputStream(new FileInputStream(zipFile), 255)); ZipEntry entry; int length; byte[] buffer = new byte[255]; while ((entry = inputStream.getNextEntry()) != null) { String filePath = baseFile.toPath().toString() + "\\" + entry.getName(); createParentPath(new File(filePath)); Files.createFile(Paths.get(filePath)); FileOutputStream outputStream = new FileOutputStream(Paths.get(filePath).toFile()); while ((length = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, length); } } }
public static void main(String[] args) { try { String zipPathStr = "F:\\cache\\test.zip"; try (ZipOutputStream zipOutputStream = new ZipOutputStream(new FileOutputStream(new File(zipPathStr)))) { for (int i = 0; i < 3; i++) { String filePathStr = "F:\\cache\\test.xls"; File file = new File(filePathStr); try (FileInputStream fileInputStream = new FileInputStream(file)) { zipFile(fileInputStream, zipOutputStream, "all/" + i + file.getName()); } } }
decompressionFile( "F:\\cache\\test.zip", "F:\\cache\\test"); } catch (Exception ex) { ex.printStackTrace(); } } }
|