zip.md 2.6 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 64 65 66 67 68 69 70 71 72 73 74 75 76
# 压缩流

已知 ZipOutputStream 是 Java 标准库的压缩输出流,那么下列哪个选项可以正确的将指定文件压缩为zip文件?

## 答案

```java
        String sourceFile = "path_to_source";
        File fileToZip = new File(sourceFile);
        try (FileOutputStream fos = new FileOutputStream("path_to_zip");
             FileInputStream fis = new FileInputStream(fileToZip);
             ZipOutputStream zipOut = new ZipOutputStream(fos);) {
            ZipEntry zipEntry = new ZipEntry(fileToZip.getName());
            zipOut.putNextEntry(zipEntry);
            byte[] bytes = new byte[1024];
            int length;
            while ((length = fis.read(bytes)) >= 0) {
                zipOut.write(bytes, 0, length);
            }
        }
```

## 选项

### 没有关闭资源

```java
        String sourceFile = "path_to_source";
        File fileToZip = new File(sourceFile);
        FileOutputStream fos = new FileOutputStream("path_to_zip");
        FileInputStream fis = new FileInputStream(fileToZip);
        ZipOutputStream zipOut = new ZipOutputStream(fos);
        ZipEntry zipEntry = new ZipEntry(fileToZip.getName());
        zipOut.putNextEntry(zipEntry);
        byte[] bytes = new byte[1024];
        int length;
        while ((length = fis.read(bytes)) >= 0) {
            zipOut.write(bytes, 0, length);
        }
```


### ZipOutputStream 不能直接读写文件,需要接入其它字节流

```java
        String sourceFile = "path_to_source";
        File fileToZip = new File(sourceFile);
        try (FileInputStream fis = new FileInputStream(fileToZip);
             ZipOutputStream zipOut = new ZipOutputStream("path_to_zip");) {
            ZipEntry zipEntry = new ZipEntry(fileToZip.getName());
            zipOut.putNextEntry(zipEntry);
            byte[] bytes = new byte[1024];
            int length;
            while ((length = fis.read(bytes)) >= 0) {
                zipOut.write(bytes, 0, length);
            }
        }
```

### 缓冲区需要初始化

```java
        String sourceFile = "path_to_source";
        File fileToZip = new File(sourceFile);
        try (FileOutputStream fos = new FileOutputStream("path_to_zip");
             FileInputStream fis = new FileInputStream(fileToZip);
             ZipOutputStream zipOut = new ZipOutputStream(fos);) {
            ZipEntry zipEntry = new ZipEntry(fileToZip.getName());
            zipOut.putNextEntry(zipEntry);
            byte[] bytes = null;
            int length;
            while ((length = fis.read(bytes)) >= 0) {
                zipOut.write(bytes, 0, length);
            }
        }
```