unzip.md 1.8 KB
Newer Older
M
Mars Liu 已提交
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
# 解压流

已知 GZIPInputStream 是 Java 标准库中用于从 gzip 格式文件读取信息的类型,那么从一个gzip文件读取信息并解压的正确实现应该是:

## 答案

```java
        String fileZip = "path_to_file.zip";
        File destDir = new File("path_to_dest");
        byte[] buffer = new byte[1024];
        try (ZipInputStream zis = new ZipInputStream(new FileInputStream(fileZip))) {
            ZipEntry zipEntry = zis.getNextEntry();
            while (zipEntry != null) {
                // ...
            }
            zis.closeEntry();
        }
```

## 选项

### 没有关闭资源

```java
        String fileZip = "path_to_file.zip";
        File destDir = new File("path_to_dest");
        byte[] buffer = new byte[1024];
        ZipInputStream zis = new ZipInputStream(new FileInputStream(fileZip)) 
        ZipEntry zipEntry = zis.getNextEntry();
        while (zipEntry != null) {
            // ...
        }
```

### zip 流需要接到字节输入流上工作

```java
        String fileZip = "path_to_file.zip";
        File destDir = new File("path_to_dest");
        byte[] buffer = new byte[1024];
        try (ZipInputStream zis = new ZipInputStream(fileZip)) {
            ZipEntry zipEntry = zis.getNextEntry();
            while (zipEntry != null) {
                // ...
            }
            zis.closeEntry();
        }
```

### 缓冲区需要分配空间

```java
        String fileZip = "path_to_file.zip";
        File destDir = new File("path_to_dest");
        byte[] buffer = null;
        try (ZipInputStream zis = new ZipInputStream(new FileInputStream(fileZip))) {
            ZipEntry zipEntry = zis.getNextEntry();
            while (zipEntry != null) {
                // ...
            }
            zis.closeEntry();
        }
```